LINQ选择取决于内部集合值

时间:2012-09-06 13:02:32

标签: 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;
}

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

您可以使用SelectMany展平列表。然后你不必做任何棘手的事情,比如在LINQ语句的中间分配一个值。

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

这是基本等效的查询语法:

sp = (from tool in Tools.GetAllItems()
      from spoon in tool.AllSpoons
      where spoon.Label == this.Label
      select spoon).FirstOrDefault();

答案 2 :(得分:0)

public bool IsSpoon(out Spoon sp) 
{ 
    return Tools.GetAllItems()
        .SelectMany(t => t.AllSpoons)
        .Any(x => x.Label == this.Label);
}