Find an item in list of objects by LINQ - C#

Find an item in list of objects by LINQ - C#


Here I have a simple example to find an item in an list of objects using LINQ Extension methods.


There are a few ways.


- Single will return a single result, but will throw an exception if it finds none or more than one.


SingleOrDefault will behave the same, except it will return null, or the default value, instead of throwing exception.


- Where will return all items which match your criteria.


- First will return the first item which matches your criteria.


FirstOrDefault will behave the same, except it will return null, or the default value, instead of throwing exception.


In my example, I will use the SingleOrDefault criteria. Then I will create a list using the Person class as shown below.


  
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }


I will add two Person objects to the list. Then I will show you the Person object with the Id value of 1 on the screen.


    List list = new List();
    list.Add(new Person { Id = 1, Name = "Elon", Surname = "Musk" });
    list.Add(new Person { Id = 2, Name = "Bill", Surname = "Gates" });

    Person p1 = list.SingleOrDefault(x => x.Id == 1);


Result :


find-item-in-list-by-linq.png

tag : linq find in list c#,linq find in list in c#