使用LINQ在嵌套集合中查找值 [英] Use LINQ to find value inside a nested collection
本文介绍了使用LINQ在嵌套集合中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下要转换为LINQ的代码段.目的是在内部集合中找到一个匹配项并返回其Data属性.有什么建议吗?
I have the following snippet of code that I'd like to convert to LINQ. The goal is to find a match in the inner collection and return its Data property. Any suggestions?
string data = null;
foreach (var section in sections)
{
foreach (var field in section.Fields)
{
if (field.Id == id)
{
data = field.Data;
}
}
}
推荐答案
Now matches
contains all the data strings that match. If you only have a single match, you can use Single
(or SingleOrDefault
if there may not be any) to get that individual value. If you might have more matches, use FirstOrDefault
or LastOrDefault
. (in your code, Last
is the method that will give you the same answer)
您可以将所有内容放在一起并简化:
You could put all that together and simplify:
data = sections
.SelectMany(s => s.Fields)
.SingleOrDefault(f => f.Id == id)
?.Data;
请注意?
,以防万一您没有匹配项.
Note the ?
just in case you have no matches.
这篇关于使用LINQ在嵌套集合中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文