【问题标题】:Lambda expression confusingLambda 表达式令人困惑
【发布时间】:2020-05-23 03:27:34
【问题描述】:

我真的对我找到并想在项目中使用的这行代码感到困惑。

public static List<test> listname = new List<test>();

return listname.Single(m => m.ID == id);

你能解释一下这个 lambda 表达式是什么意思,然后用不使用 lambda 表达式的非常简单的格式重写它吗?

【问题讨论】:

  • 这能回答你的问题吗? What's the point of a lambda expression?
  • 您显示的代码不完整(即它们不能处于同一级别)。虽然您可以避免使用Single,但这样做会更加冗长。我认为这 简单(这与您可能遇到的 LINQ 用法一样简单)。
  • 相当于return (from item in listname where item.ID == id select item).Single();,它在您的列表中查找具有所需ID 的一项。如果有 0 个匹配项或多个匹配项,它将抛出

标签: c# lambda


【解决方案1】:

让我们打开它:

return listname.Single(m => m.ID == id)

Single() 断言在 lambda 的整个集合中必须只有一个匹配。

如果我们在没有 LINQ 的情况下重写它,它可能看起来像这样:

Item GetOneAndOnlyOneItemWithId(List<Item> items, string id)
{
    if (items is null) throw new ArgumentNullException("source can't be null");
    Item match = null;
    foreach (var item in items)
    {
        if (item.Id == id)
        {
            if (match != null) throw new InvalidOperationException("There is more than 1 match!");
            match = item;
        }
    }
    if (match == null) throw new InvalidOperationException("no matchez");
    return match;
}

如您所见,它比使用 LINQ 复杂得多。 Single() 包含很多断言,而不是 FirstOrDefault() 例如。您对编程和 .NET 了解得越多,LINQ 对您就越有用。 LINQ 存在,因此我们不必为像这样的一般数据争吵重新发明轮子。它建立在 generics 之上,允许跨任何类型的 IEnumerable 重用通用逻辑。换句话说,不要与 LINQ 对抗,学习它!

【讨论】:

  • 谢谢。我不能直接写这个吗? return (from item in listname where item.ID == id select item).Single();
  • 不知道为什么要编写这么多代码,如果您可以通过一次调用来处理它?你只需要习惯这个符号,相信我,它会为你顺利工作。
  • @Tekimoto 你可以,但这只是你问题中 LINQ 的一个更详细的版本。两种形式都使用 LINQ。
【解决方案2】:

该代码从字面上返回 ID 属性等于 id 值的项目。将返回单个项目。

查看 this 和 First() 之间区别的好帖子是这个:LINQ Single vs First

【讨论】:

    【解决方案3】:

    您正在使用的这个 lambda 表达式返回列表中 item.Id 等于参数 id 的出现项。

    我将尝试用 foreach 迭代来解释。希望你能理解。

    foreach (var item in listName)
    {
          if(item.Id == id)
          {
           return item;
             ```
             As it had an occurence here this may be the value returned but if comes again 
          to this point it will throw an exception.
          This describes it best:
          "It returns a single specific element from a collection of elements if element 
          match found. An exception is thrown, if none or more than one match found for 
          that element in the collection."
            ```
           }
    }
    

    但我建议您改用 .FirstOrDefault()。 更多信息在这里:https://www.dotnettricks.com/learn/linq/understanding-single-singleordefault-first-and-firstordefault

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 2011-01-24
      相关资源
      最近更新 更多