简体   繁体   English

LINQ:在子列表中创建条件 Where 子句

[英]LINQ: Create a Conditional Where Clause in child list

I need help to build a "query" using LINQ `where". I'm not getting this alone.我需要帮助来使用 LINQ `where" 构建“查询”。我不是一个人解决这个问题。

I need to create a conditional clause, but into a child list.我需要创建一个条件子句,但放入子列表中。

By the way, here is an example.顺便说一下,这里有一个例子。

public void Main{
    List<Father> Fathers = getFathers(); 

    //How can I create this clause? 
    Fathers.Where(x=>x.age > 50 && x.ChildrenGirl.Where(y=>y.ID == 5))

}

public class Father{
    public int ID { get; set; }
    public int age {get; set;}
    public List<ChildGirl> ChildrenGirl  { get; set; }
    public List<ChildBoy> ChildrenBoy { get; set; }
}

public class ChildGirl{
    public int ID { get; set; }
    public int power {get;set;}
}

public class ChildBoy{
    public int ID { get; set; }
    public int power {get;set;}
}

您可以使用Any函数来检查是否至少存在一个条件

   Fathers.Where(x => x.age > 50 && x.ChildrenGirl.Any(y => y.ID == 5));

First make all your properties public.首先公开你的所有属性。 Nothing will work without that.没有它,什么都行不通。

You may find using the query comprehension syntax is easier for queries like this.您可能会发现对于这样的查询,使用查询理解语法更容易。 This is the query you are looking for, using that syntax:这是您正在寻找的查询,使用该语法:

 var result = from father in GetFathers()
     from girl in father.ChildrenGirl
     where father.age > 50 && girl.ID == 5
     select father;

When you are updating your question, you should provide an implementation of GetFathers() that fills up a collection of Father objects, each with some children.当您更新您的问题时,您应该提供一个GetFathers()的实现来填充Father对象的集合,每个对象都有一些子对象。 I'd have tested my code a lot more if you had done that.如果你这样做了,我会更多地测试我的代码。

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

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