展开具有嵌套对象集合的LINQ集合对象 [英] Flatten LINQ collection object with nested object collections
问题描述
这是一个棘手的问题。我试图压平一个LINQ对象集合。集合中的每个项目都有可能拥有两个其他对象的集合。见下面的例子。
This is a tricky one. I an trying to flatten a LINQ object collection. Each item in the collection has the potential of having two collections of other objects. See the example below.
public class DemoClass
{
public string Name {get; set;}
public string Address {get; set;}
public List<Foo> Foos = new List<Foo>();
public List<Bar> Bars = new List<Bars>();
}
我一直在做的是使用这个代码块展开这个对象
What I had been doing is this using this code block to flatten this object
var output = from d in DemoClassCollection
from f in d.Foos
from b in d.Bars
select new {
d.Name,
d.Address,
f.FooField1,
f.FooField2,
b.BarField1,
b.BarField2
};
但我遇到的问题是,我得到的结果是 >那些在Foos和Bars集合中有对象的DemoClass对象。我需要获取DemoClass中的所有对象,无论在Foos和Bars集合中是否有对象。
But the problem I'm having is that the result I get is only those DemoClass objects that have objects in the Foos and Bars collections. I need to get all objects in the DemoClass regardless if there are objects in the Foos and Bars collections.
任何帮助都将非常感激。
Any help would be greatly appreciated.
谢谢!
推荐答案
听起来你可能想使用 DefaultIfEmpty
:
var output = from d in DemoClassCollection
from f in d.Foos.DefaultIfEmpty()
from b in d.Bars.DefaultIfEmpty()
select new {
d.Name,
d.Address,
FooField1 = f == null ? null : f.FooField1,
FooField2 = f == null ? null : f.FooField2,
BarField1 = b == null ? null : b.BarField1,
BarField2 = b == null ? null : b.BarField2
};
这篇关于展开具有嵌套对象集合的LINQ集合对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!