The LINQ (Language Integrated Query) has the extension methods SingleOrDefault and FirstOrDefault . What is the difference between SingleOrDefault and FirstOrDefault in LINQ.
In one of my previous blog post , I wrote about .First() throws Error in LINQ or Entity Framework Queries which explains the use of FirstOrDefault in LINQ.
But , there is also a extension method SingleOrDefault() in LINQ .
Examples and demonstration of SingleOrDefault() and FirstOrDefault() in LINQ
The Below example illustrates the usage of SingleOrDefault() and FirstOrDefault()
public class Movie { public string MovieName { get; set; } public string Actor { get; set; } public string Director { get; set; } public string Boxoffice { get; set; } } public class Movies : List<Movie> { public Movies() { Add(new Movie { Actor = "Vijay", Director = "Murugadas", MovieName = "Thuppaki" }); Add(new Movie { Actor = "Ajith Kumar", Director = "Chakri", MovieName = "Billa 2" }); Add(new Movie { Actor = "Vijay", Director = "Shankar", MovieName = "Nanban" }); Add(new Movie { Actor = "Surya", Director = "KV Anand", MovieName = "Maatran" }); Add(new Movie { Actor = "Vijay", Director = "Jayam Raja", MovieName = "Velayutham" }); } } private void Form1_Load(object sender, EventArgs e) { List<Movie> movies = new Movies(); var data = movies.FirstOrDefault(a => a.Actor == "Vijay"); var data1 = movies.SingleOrDefault(a => a.Actor == "Vijay"); }
What is the difference between SingleOrDefault and FirstOrDefault in LINQ ?
The SingleOrDefault states that the query should return only single result whereas FirstOrDefault can return multiple result but the developer can specify that only the first one will be picked.
If the result set returns more than one record , SingleOrDefault throws “Invalid Operations Exception” – Sequence contains more than one matching element as described in the below screenshot.
Both SingleOrDefault and FirstOrDefault returns the default value for the type if the result of the query is 0 records.