使用LINQ在嵌套集合中查找值 [英] Use LINQ to find value inside a nested collection

查看:85
本文介绍了使用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;
            }
        }
    }

推荐答案

您可以使用现在matches包含所有匹配的数据字符串.如果只有一个匹配项,则可以使用Single(如果可能没有任何匹配项,则使用SingleOrDefault)来获取该单个值.如果您可能有更多匹配项,请使用FirstOrDefaultLastOrDefault. (在您的代码中,Last是将为您提供相同答案的方法)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆