簡體   English   中英

在列表項中查找列表項

[英]Finding a list item within a list item

我對這是如何工作有點困惑。

class TestClass
{
    public int ID {get;set;}
    public List<Stuff> StuffList {get; set;}
}
class Stuff
{
    public int ID {get;set;}
    public string Description {get;set;}
}

所以每個TestClass都有一個Stuff列表。 我想要做的是找到一個包含任何ID0 StuffTestClass

List<TestClass> TestList = RetrieveAllTestLists();
//Pseudocode:
//
// Find all TestClass in TestList that contain a Stuff with ID == 0;

我試過這個,但它不起作用:

List<TestClass> TestList = RetrieveAllTestLists().Where(x=> x.StuffList.Where(y=> y.ID == 0)).ToList();

誰能向我解釋我做錯了什么?

你可以使用Any

List<TestClass> TestList = RetrieveAllTestLists().
                           Where(x => x.StuffList.Any(y=> y.ID == 0)).ToList();

Basicaly Where會選擇滿足條件(這些返回所有行true ),但在這個地方,你有另一個Where 如果滿足給定條件的任何行,則Any將返回true

List<TestClass> TestList = RetrieveAllTestLists().Where(x=> x.StuffList.Any(y=> y.ID == 0)).ToList();

Any()表示至少對於一個元素或IEnumerable,參數中給出的謂詞返回true

暫無
暫無

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

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