Thursday, May 16, 2024

Difference between First, FirstOrDefault, Single, SingleOrDefault

 

See the below example I am adding 4 items to list with 1 duplicate and calling these methods, output written with comments side by method call.

            Base b1 = new Base() { Id = 1, Name = "base1" };

            Base b2 = new Base() { Id =2, Name = "base2" };

            Base b3 = new Base() { Id = 3, Name = "base3" };

            List<Base> lst = new List<Base> { b1, b2, b3, b1 };

            Base b4 = new Base { Id = 4, Name = "base4" };

            var findfirst= lst.Find(x => x.Id == 9);

            var firstElement = lst.First(x => x.Id == 9);//exception

            var firstOrDefaultTest = lst.FirstOrDefault(x => x.Id == 90); //null, default value;

            var singleOrdefaulttest = lst.SingleOrDefault(x => x.Id == 1);// exception because found more than 1 element for Id=1. no exception In-case not found.

            var singleTest = lst.Single(x => x.Id == 90);//exception if not found also if found duplicate.

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...