簡體   English   中英

使用LINQ在父對象列表中查找子對象

[英]Find child objects in list of parent objects using LINQ

給定一個Parent對象列表,每個對象都有一個Child對象列表,我想找到與特定ID匹配的子對象。

public class Parent
{
    public int ID { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public int ID { get; set; }
}

現在我希望Child對象具有特定的ID:

List<Parent> parents = GetParents();
Child childWithId17 = ???

我怎么能用Linq做到這一點?

我想你想要:

Child childWithId17 = parents.SelectMany(parent => parent.Children)
                             .FirstOrDefault(child => child.ID == 17);

請注意,這假定Parent的Children屬性不是null引用或包含null Child引用。

您可以使用SelectMany:

Child childWithId17 = parents.SelectMany(p => p.Children)
                             .Where(ch=>ch.ID==17)
                             .FirstOrDefault();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM