繁体   English   中英

从嵌套子列表中删除空对象列表

[英]Removing an empty list of objects from a nested sublist

我有一个对象Foo ,其中包含一个List<Bar>

Bar包含一个List<Baz>

Baz包含一个List<Qux>

Qux有一个我想比较的属性。

如果我有List<Foo> ,如何从List<Qux>为空的列表中过滤掉所有Foo对象?

编辑更新了我的问题以更恰当地反映我的问题。

如果您想在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));

如果您想在其下的所有Qux都具有特定值时保留Foo ,请将Any替换为All

你也可以用更清晰的语法来做到这一点(就像我在那种情况下)

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;

感谢@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();
}
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 { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM