HI WELCOME TO SIRIS
Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Understanding Single, SingleOrDefault, First and FirstOrDefault

LINQ provides element operators which return a single element or a specific element from a collection. The elements operators are Single, SingleOrDefault, First, FirstOrDefault, Last, LastOrDefault.

Single

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.

SingleOrDefault

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if more than one match found for that element in the collection. A default value is returned, if no match is found for that element in the collection.
  1. List<int> data = new List<int> { 10, 20, 30, 40, 50 };
  2.  
  3. //Try to get element at specified position
  4. Console.WriteLine(data.ElementAt(1)); //result:20
  5.  
  6. //Try to get element at specified position if exist, else returns default value
  7. Console.WriteLine(data.ElementAtOrDefault(10)); //result:0, since default value is 0
  8.  
  9. Console.WriteLine(data.First()); //result:10
  10. Console.WriteLine(data.Last()); //result:50
  11.  
  12. //try to get first element from matching elements collection
  13. Console.WriteLine(data.First(d => d <= 20)); //result:10
  14.  
  15. //try to get first element from matching elements collection else returns default value
  16. Console.WriteLine(data.SingleOrDefault(d => d >= 100)); //result:0, since default value is 0
  17.  
  18. //Try to get single element
  19. // data.Single(); //Exception:Sequence contains more than one element
  20.  
  21. //Try to get single element if exist otherwise returns default value
  22. // data.SingleOrDefault(); //Exception:Sequence contains more than one element
  23.  
  24. //try to get single element 10 if exist
  25. Console.WriteLine(data.Single(d => d == 10)); //result:10
  26.  
  27. //try to get single element 100 if exist otherwise returns default value
  28. Console.WriteLine(data.SingleOrDefault(d => d == 100)); //result:0, since default value is 0

First

It returns first specific element from a collection of elements if one or more than one match found for that element. An exception is thrown, if no match is found for that element in the collection.

FirstOrDefault

It returns first specific element from a collection of elements if one or more than one match found for that element. A default value is returned, if no match is found for that element in the collection.

When to use Single, SingleOrDefault, First and FirstOrDefault

You should take care of following points while choosing Single, SingleOrDefault, First and FirstOrDefault:
  1. When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
  2. When you want a default value is returned if the result set contains no record, use SingleOrDefault.
  3. When you always want one record no matter what the result set contains, use First or FirstOrDefault.
  4. When you want a default value if the result set contains no record, use FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault

FirstOrDefault usually perform faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.
What do you think?
I hope you will enjoy LINQ element operators programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Difference between Select and SelectMany in LINQ

Select and SelectMany are projection operators. Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.
Select operator produce one result value for every source value while SelectMany produce a single result that contains a concatenated value for every source value. Actually, SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.
  1. class Employee
  2. {
  3. public string Name { get; set; }
  4. public List<string> Skills { get; set; }
  5. }
  6.  
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. List<Employee> employees = new List<Employee>();
  12. Employee emp1 = new Employee { Name = "Deepak", Skills = new List<string> { "C", "C++", "Java" } };
  13. Employee emp2 = new Employee { Name = "Karan", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };
  14.  
  15. Employee emp3 = new Employee { Name = "Lalit", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };
  16.  
  17. employees.Add(emp1);
  18. employees.Add(emp2);
  19. employees.Add(emp3);
  20.  
  21. // Query using Select()
  22. IEnumerable<List<String>> resultSelect = employees.Select(e=> e.Skills);
  23.  
  24. Console.WriteLine("**************** Select ******************");
  25.  
  26. // Two foreach loops are required to iterate through the results
  27. // because the query returns a collection of arrays.
  28. foreach (List<String> skillList in resultSelect)
  29. {
  30. foreach (string skill in skillList)
  31. {
  32. Console.WriteLine(skill);
  33. }
  34. Console.WriteLine();
  35. }
  36.  
  37. // Query using SelectMany()
  38. IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills);
  39.  
  40. Console.WriteLine("**************** SelectMany ******************");
  41.  
  42. // Only one foreach loop is required to iterate through the results
  43. // since query returns a one-dimensional collection.
  44. foreach (string skill in resultSelectMany)
  45. {
  46. Console.WriteLine(skill);
  47. }
  48.  
  49. Console.ReadKey();
  50. }
  51. }
  52.  
  53. /* Output
  54. **************** Select ******************
  55.  
  56. C
  57. C++
  58. Java
  59.  
  60. SQL Server
  61. C#
  62. ASP.NET
  63.  
  64. C#
  65. ASP.NET MVC
  66. Windows Azure
  67. SQL Server
  68.  
  69. **************** SelectMany ******************
  70.  
  71. C
  72. C++
  73. Java
  74. SQL Server
  75. C#
  76. ASP.NET
  77. C#
  78. ASP.NET MVC
  79. Windows Azure
  80. SQL Server
  81. */
What do you think?
I hope you will enjoy Select and SelectMany while programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.