Vinay  Arora
What is the difference between First() and Single() extension methods in LINQ?
By Vinay Arora in LINQ on May 31 2013
  • Smart    Lucky
    Sep, 2014 17

    1.) First() : Suppose you have sequence(list) contains duplicate elements and you are going to find "item" and this word is three time in list on different indexes, the first() method will start the searching as it find the item it will return and leave others. listFirstOrDefault(l => l.Equals("item")); 2.)Single() if item are more than two in list it will throw exception.

    • 1
  • Munesh Sharma
    Jun, 2015 16

    http://www.dotnetfunda.com/interviews/show/4777/what-is-the-difference-between-first-and-single-extension-methods-in-l

    • 0
  • Bhabani Prasad
    May, 2014 21

    1. First() returns the first element of a sequence even there is a single element in that sequence. 2. Single() returns the single element of a sequence and that element should be the exactly a single one. If there are more then one matching elements the exception is thrown. It means using Single() method is some kind of consistency check. Pay attentions to that fact and find the appropriate use to this method. When you use Single() you should know that matching element is always only one.**-If you want an exception to be thrown if the sequence contains more than one element, then use SingleOrDefault. If you always want one record no matter what the sequence contains, use FirstOrDefault.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS