[英]c# - query nested type with LINQ
我有一個如下所示的模型:
public class MyType{
public string Id {get;set;}
public string Name{get;set;}
public List<MyType> Children{get;set;}
}
在我的數據中,我只有兩個級別的數據,這意味着我的對象將如下所示:
{
MyType{"1","firstParent",
{
MyType{"2","firstChild",null},
MyType{"3","secondChild",null}}
},
MyType{"4","secondParent",
{
MyType{"5","firstChild",null},
MyType{"6","secondChild",null}}
}
}
如何查詢MyType對象的特定Id,它可能是父或子?
以下將僅返回父母。
collection.FirstOrDefault(c => c.id==id)
您可以使用Any
與遞歸本地函數來查找任何級別的對象(您的數據結構似乎表明可能更深層次)
bool hasIdOrChildren(MyType t, string localId)
{
return t.Id == localId || (t.Children != null && t.Children.Any(o => hasIdOrChildren(o, localId)));
}
collection.FirstOrDefault(c => hasIdOrChildren(c, id));
或者使用pre C#7語法:
Func<MyType, string, bool> hasIdOrChildren = null;
hasIdOrChildren = (MyType t, string localId) =>
{
return t.Id == localId || (t.Children != null && t.Children.Any(o => hasIdOrChildren(o, localId)));
};
collection.FirstOrDefault(c => hasIdOrChildren(c, id));
如果您只對一個級別感興趣,可以放棄隱遁:
collection.FirstOrDefault(c => c.Id == id || (c.Children != null && c.Children.Any(o => o.Id == id)));
編輯
上面的代碼給出了父代如果任何子代碼具有id,你也可以使用SelectMany
使用遞歸函數展平整個樹結構:
IEnumerable<MyType> flattenTree(MyType t)
{
if(t.Children == null)
{
return new[] { t };
}
return new[] { t }
.Concat(t.Children.SelectMany(flattenTree));
};
collection
.SelectMany(flattenTree)
.FirstOrDefault(c => c.Id == id);
此方法可用於需要展平樹的任何類型的處理。
您可以構建包含子項的所有MyType的列表,然后像這樣查詢:
collection.SelectMany(c => c.Children).Concat(collection).Where(c => c.id == id)
我想你在找
var flattenedList = IEnumerable.SelectMany(i => i.ItemsInList);
這會使列表變平,並返回一個列表,其中包含所有項目。 在您的情況下,您需要選擇
collection.SelectMany(c => c.Type).Concat(collection).Where(item => item.Id == 5);
你仍然在這里加入了父母的孩子,但你仍然可以刪除它們或忽略它們。
我認為,你應該使用SelectMany方法展平collection
,然后使用FirstOrDefault
按id
獲取元素:
MyType selected = collection
.SelectMany(obj => new MyType[] {obj, obj.NestedList})
.FirstOrDefault(obj => obj.id == id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.