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

时间:2015-11-24 23:21:12

标签: c# linq

我有一个对象$("#example-one li").hover(function() { $el = $(this); leftPos = $el.position().left; newWidth = $el.width(); ,其中包含Foo

List<Bar>包含Bar

List<Baz>包含Baz

List<Qux>有一个我要比较的属性。

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

修改 更新了我的问题以更恰当地反映我的问题。

4 个答案:

答案 0 :(得分:0)

如果您希望在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下的所有Any具有特定值,请将All替换为var view = { "rows": [ { "CustomerName": "abc", "key": "value", "keyabc": "value" }, { "CustomerName": "abc", "key": "value", "keyabc": "value" }, { "CustomerName": "abc", "key": "value", "keyabc": "value" } ] };

答案 1 :(得分:0)

您也可以使用更清晰的语法(就像我这样的情况)

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;

答案 2 :(得分:0)

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

答案 3 :(得分:0)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


    connection.Open()

    'It comes here after opening the connection

    Dim command As New OleDb.OleDbCommand("Requestor Name", connection)


    Dim reader As OleDb.OleDbDataReader

    reader = command.ExecuteReader()

    Do While (reader.Read())

        QUERBOX.Items.Add(reader.GetInt32(0))

    Loop

    reader.Close()

    connection.Close()
End Sub

这应该适用于每个<dial>都没有空foos.Where(f=>f.Bars.All(bar=>bar.Bazs.All(baz=>baz.Quxs.Any())>))

的情况
baz