c# - LINQ 根据内部集合值选择

标签 c# linq select collections

我有这段代码:

public string Label { get; set; }

public bool IsSpoon(out Spoon sp) 
{
    sp = null;
    foreach (Tool t in Tools.GetAllItems())
        if ((sp = t.AllSpoons.FirstOrDefault(x => x.Label == this.Label)) != null)
            break;

    return sp != null;
}

如何通过 LINQ 对其进行优化?

我想到了这样的事情,但这是不允许的:

public string Label { get; set; }

public bool IsSpoon(out Spoon sp) 
{
    return Tools.GetAllItems().FirstOrDefault(x => (sp = x.AllSpoons.FirstOrDefault(y => y.Label == this.Label)) != null) != null;
}

最佳答案

编辑: 我没有注意到 sp 参数,这里有一个更新:

sp = Tools
    .GetAllItems()
    .SelectMany(x => x.AllSpoons)
    .FirstOrDefault(y => y.Label == this.Label);
return sp != null;

关于c# - LINQ 根据内部集合值选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12300751/

相关文章:

c# - 寻找十进制数据的直方图分箱算法

c# - HTTPS POST Web 服务请求格式 - 在子节点内插入多个值

MySQL 在同一个表上使用不同 WHERE 子句进行多个 SELECT 查询

SQL INSERT INTO SELECT - 现有行

vb.net - VB.NET lambda 表达式示例

mysql - 图表数据的 SQL 查询帮助

c# - 包含实例方法委托(delegate)的静态字典

c# - 添加更多我的用户控件容器或用户控件集合显示

c# - 系统参数异常 : Parameter is not valid

c# - 使用 LINQ 按内部 Dictionary 值的值对 Dictionary<string,Dictionary<string,string>> 进行排序?