3

我有这段代码:

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;
}
4

3 回答 3

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();
于 2012-09-06T13:17:49.007 回答
2

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

sp = Tools
    .GetAllItems()
    .SelectMany(x => x.AllSpoons)
    .FirstOrDefault(y => y.Label == this.Label);
return sp != null;
于 2012-09-06T13:06:21.050 回答
0
public bool IsSpoon(out Spoon sp) 
{ 
    return Tools.GetAllItems()
        .SelectMany(t => t.AllSpoons)
        .Any(x => x.Label == this.Label);
}
于 2012-09-06T13:05:17.497 回答