我有一个对象,Foo
其中包含一个List<Bar>
。从嵌套子列表中删除对象的空列表
Bar
包含List<Baz>
。
Baz
包含List<Qux>
。
Qux
有一个属性,我想比较。
如果我有List<Foo>
,如何过滤掉List<Qux>
为空的列表中的所有Foo
对象?
编辑 更新我的问题,以更恰当地反映我的问题。
我有一个对象,Foo
其中包含一个List<Bar>
。从嵌套子列表中删除对象的空列表
Bar
包含List<Baz>
。
Baz
包含List<Qux>
。
Qux
有一个属性,我想比较。
如果我有List<Foo>
,如何过滤掉List<Qux>
为空的列表中的所有Foo
对象?
编辑 更新我的问题,以更恰当地反映我的问题。
感谢@ 31eee384为把我在正确的轨道上。
我还合并了Except()
扩展名以删除空列表。我相信有一种更有效的方法来写这篇文章,所以,如果你知道其中一篇,请发帖。
这是我创建的扩展方法。
internal static List<Foo> OnlyWithQuxs(this List<Foo> model)
{
var foosToRemove = new List<Foo>();
foreach (var foo in model)
{
var barsToRemove = new List<Bar>();
foreach (var bar in foo.bars)
{
var bazWithQux = new List<Baz>();
var bazsToRemove = new List<Baz>();
foreach (var baz in bar.bazs)
{
baz.Quxs = GetbazQuxs(baz.Id)
.Where(qux => qux.Property == someValue)
.ToList();
bazWithQux.Add(baz);
if (baz.Quxs == null || baz.Quxs.Count() == 0)
bazsToRemove.Add(baz);
}
bar.bazs = bazWithQux.Except(bazsToRemove).ToList();
if (bar.bazs == null || bar.bazs.Count() == 0)
barsToRemove.Add(bar);
}
foo.bars = foo.bars.Except(barsToRemove).ToList();
if (foo.bars == null || foo.bars.Count() == 0)
foosToRemove.Add(foo);
}
return model.Except(foosToRemove).ToList();
}
如果你想保持Foo
时存在一些Qux
下,它具有一定的价值,做到这一点:
List<Foo> foos = ...;
IEnumerable<Foo> query = foos
.Where(foo => foo.Bars
.SelectMany(bar => bar.Bazs)
.SelectMany(baz => baz.Quxs)
.Any(qux => qux.SomeProperty == someValue));
如果你想保持Foo
当所有Qux
下,它有一定的价值,用All
代替Any
。
您也可以用更清晰的语法(在这种情况下,像我)做
List<Foo> lst = GetFooList();
var foos = from foo in lst
from bar in foo.Bars
from baz in bar.Bazs
from qux in baz.Quxs
where qux.Property != somevalue
select foo;
foos.Where(f=>f.Bars.All(bar=>bar.Bazs.All(baz=>baz.Quxs.Any())>))
这应该工作,每一个baz
不会有一个空List<Qux>
var foos = new List<Foo>
{
new Foo {Bars = new List<Bar> {new Bar { Bazs = new List<Baz> { new Baz { Quxs = new List<Qux> { new Qux()} } } } } },
new Foo {Bars = new List<Bar> {new Bar { Bazs = new List<Baz> { new Baz { Quxs = new List<Qux> { new Qux()} } } } } },
new Foo {Bars = new List<Bar> {new Bar { Bazs = new List<Baz> { new Baz { Quxs = new List<Qux> { } } } } } },
};
var r = foos.Where(f => f.Bars.All(bars=>bars.Bazs.All(baz=>baz.Quxs.Any()))).ToList();
class Foo
{
public List<Bar> Bars { get; set; }
}
class Bar
{
public List<Baz> Bazs { get; set; }
}
class Baz
{
public List<Qux> Quxs { get; set; }
}
class Qux { }
假设你'listFoo'是你Foo'的'名单,然后我们有'变种filteredListFoo = listFoo.Select (bar => bar.Select(baz => baz.Select(qux => qux.myproperty =='somevalue')))' –
编辑表明结构是递归的。这是真的?这将使问题更容易理解和回答更容易。 – 31eee384
它是递归的。 – Ian