-2

I am really confused with this line of code that I have found and want to use in a project.

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

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

Can you please explain what this lambda expression means and then re-write it in a very simple format that does not use lambda expression?

GSerg
  • 76,472
  • 17
  • 159
  • 346
Tekimoto
  • 5
  • 2
  • 1
    Does this answer your question? [What's the point of a lambda expression?](https://stackoverflow.com/questions/5873603/whats-the-point-of-a-lambda-expression) – taha May 22 '20 at 18:58
  • 1
    The code you are showing is not complete (i.e. they cannot be at the same level). And while you could avoid the `Single`, to do so would be more verbose. I would argue that that *is* simple (and that is about as simple of a LINQ usage you could encounter). – crashmstr May 22 '20 at 19:00
  • It is equivalent to `return (from item in listname where item.ID == id select item).Single();` it's finding the one item in your list that has the desired ID. It will throw if there are 0 matches or more than one match – Flydog57 May 22 '20 at 19:06

3 Answers3

2

Let's unpack it:

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

Single() asserts that there MUST be one and only one match in the entire collection for the lambda.

If we were to rewrite this without LINQ it might look like this:

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

As you can see, it's much more complex than using LINQ. Single() contains a lot of assertions, as opposed to FirstOrDefault() for example. The more you learn about programming and .NET the more useful LINQ will be to you. LINQ exists so we do not have to re-invent the wheel for general data-wrangling like this. It is built upon generics which allows common logic to be re-used across IEnumerables of any types. In other words, don't fight LINQ, learn it!

Timothy Jannace
  • 1,401
  • 12
  • 18
  • Thanks.Can't I just write this instead? return (from item in listname where item.ID == id select item).Single(); – Tekimoto May 22 '20 at 19:24
  • Not sure why you would want to write that much code, if you can handle it with a single call? You just have to get used to the notation and it will work smoothly for you, trust me. – Ramon Brokking May 22 '20 at 19:26
  • 2
    @Tekimoto you could but that's just a more verbose version of the LINQ in your question. And both forms are using LINQ. – quaabaam May 22 '20 at 19:34
0

The code literally returns the item which has an ID property equal to the value of id. A single item will be returned.

A good post to see the difference between this and First() is this one: LINQ Single vs First

Ramon Brokking
  • 55
  • 2
  • 2
  • 10
0

This lambda expression you are using return the an occurence item of the list in which item.Id is equal to parameter id.

I will try to explain with a foreach iteration. Hope you understand it.

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."
        ```
       }
}

But i recommend you using .FirstOrDefault() instead. More information here : https://www.dotnettricks.com/learn/linq/understanding-single-singleordefault-first-and-firstordefault

Flori Bruci
  • 436
  • 4
  • 11