选择多个类属性
问题描述:
下面的代码采用C类的集合,并创建由两个属性A和B A和B被置于同一集合内的值的集合:选择多个类属性
class A
{
public int x { get; set; }
}
class B
{
public int x { get; set; }
}
class C
{
public A A { get; set; }
public B B { get; set; }
}
..........
var items = new List<C>()
{
new C()
{
A = new A() {x = 1},
B = new B() {x = 2}
},
new C()
{
A = new A() {x = 3},
B = new B() {x = 4}
},
};
var qA = from item in items
select (object)item.A;
var qB = from item in items
select (object)item.B;
var qAll = qA.Concat(qB);
可以用一个查询来做到这一点吗?
答
如果你真的想扁平化这样的特性,你可以喂阵列SelectMany():
var qAll = items.SelectMany(item => new object[] { item.A, item.B });
是'items'一个IList的''?你为什么要把'item.A'和'item.B'加到'object'? –
Jason
是的。项目是IList。我现在更新了代码。我投A和B来反对,所以我可以把它们放在一个集合中。真正的代码没有这样做,我使用A和B继承的接口,但它并不重要。问题中的代码只是为了展示这个想法。 –
Max