3
Reply

What is the difference between First() and Single() extension methods in LINQ?

Vinay  Arora

Vinay Arora

May 31, 2013
2.7k
0

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

    Munesh Sharma
    June 16, 2015
    0

    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.

    Smart Lucky
    September 17, 2014
    0

    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.

    Bhabani Prasad
    May 21, 2014
    0