Get the specific element in nested list using lambda in c#
美好的日子,
假设我有一个静态的
我要做的是
1 2 3 4 5 6 7 8 9 10 11 12 13 | foreach(AClass a in myStaticList) { foreach(BClass b in a.bList) { foreach(CClass c in b.cList) { if(c.CId == 12345) { c.Name ="Specific element in static list is now changed."; } } } } |
我能用linq lambda表达式实现这个吗?
类似的东西;
1 2 3 4 5 6 | myStaticList .Where(a=>a.bList .Where(b=>b.cList .Where(c=>c.CId == 12345) != null) != null) .something logical .Name ="Specific element in static list is now changed."; |
请注意,我想更改静态列表中特定项的属性。
您需要
1 2 3 4 5 6 | var result = myStaticList.SelectMany(a=>a.bList) .SelectMany(b => b.cList) .FirstOrDefault(c => c.CId == 12345); if(result != null) result.Name ="Specific element in static list is now changed.";; |
使用
1 2 3 4 5 6 | var element = myStaticList.SelectMany(a => a.bList) .SelectMany(b => b.cList) .FirstOrDefault(c => c.CId == 12345); if (element != null ) element.Name ="Specific element in static list is now changed."; |
1 2 3 4 5 6 7 8 9 | var item = (from a in myStaticList from b in a.bList from c in b.cList where c.CID = 12345 select c).FirstOrDefault(); if (item != null) { item.Property ="Something new"; } |
也可以使用selectmany,但这并不简单。