LINQ provides with two extension methods SingleOrDefault and FirstOrDefault. Let's see the difference between the two. Add a new class clsTest and add two properties Id and Name. Create a List clsTest type, add some data. So we have the following code:
- static void Main(string[] args)
- {
- List<clsTest> lstTest = new List<clsTest>();
- lstTest.Add(new clsTest
- {
- Id = 1,
- Name = "A"
- });
- lstTest.Add(new clsTest
- {
- Id = 2,
- Name = "B"
- });
- lstTest.Add(new clsTest
- {
- Id = 3,
- Name = "C"
- });
- var fod = lstTest.Where(l => l.Name == "D").FirstOrDefault();
- var sod = lstTest.Where(l => l.Name == "D").SingleOrDefault();
- }
Here, we are access an element which does not exist in the list. Run the application and we get null. So both of these methods handle the null condition. Now let's add duplicate records and search the record. So the code changes to:
- static void Main(string[] args)
- {
- List<clsTest> lstTest = new List<clsTest>();
- lstTest.Add(new clsTest
- {
- Id = 1,
- Name = "A"
- });
- lstTest.Add(new clsTest
- {
- Id = 2,
- Name = "B"
- });
- lstTest.Add(new clsTest
- {
- Id = 3,
- Name = "C"
- });
- lstTest.Add(new clsTest
- {
- Id = 4,
- Name = "C"
- });
- var fod = lstTest.Where(l => l.Name == "C").FirstOrDefault();
- var sod = lstTest.Where(l => l.Name == "C").SingleOrDefault();
- }
Now run the application. We get the exception Sequence contains more than one element for SingleOrDefault. FirstOrDefault returns the first matching record i.e. the record with Id=3. However, This is because, SingleOrDefault cannot handle the situation if there are multiple elements with the same name. However, FirstOrDefault will return the first matching record from the list. Happy coding...!!!
No comments:
Post a Comment