如何根据LINQ中子级的属性过滤对象

时间:2018-06-26 14:23:41

标签: c# linq

我所拥有的人员列表,每个人都具有作为属性的Recoding(类)列表。 列表中有几个对象。 如果这些对象之一不为空,我想将该人添加到新列表中。

我是用foreach循环完成的,但是它如何在LINQ中工作?

List<Individual> Persons = new List<Person>();

foreach (Person person in Persons)
{
    foreach (Recording recording in person.Recordings)
    {
        if (recording.myProperty != "")
        {
            if (!Foo.Contains(person))
            {
                Foo.Add(person);
            }
        }
    }
}

Persons = Foo;

1 个答案:

答案 0 :(得分:2)

看来 Linq 应该是这样的:

List<Individual> Foo = Persons
  .Where(person => person.Recordings
     .Any(recording => (recording.myProperty != "")))
// .Distinct() // <- Uncomment if Persons contains duplicates
  .ToList();

我们扫描所有Persons,并获得所有至少具有一个recording且值不为myProperty的项目。