재우니의 블로그

c# 의 Linq 에서 Single, SingleOrDefault, First , FirstOrDefault 차이점 이해하기

 

 

 

 

https://www.dotnettricks.com/learn/linq/understanding-single-singleordefault-first-and-firstordefault

 

Understanding Single, SingleOrDefault, First and FirstOrDefault

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, LastOrDe

www.dotnettricks.com

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.

 

List<int> data = new List<int> { 10, 20, 30, 40, 50 };

//Try to get element at specified position
Console.WriteLine(data.ElementAt(1)); //result:20 

//Try to get element at specified position if exist, else returns default value
Console.WriteLine(data.ElementAtOrDefault(10)); //result:0, since default value is 0 

Console.WriteLine(data.First()); //result:10 
Console.WriteLine(data.Last()); //result:50

//try to get first element from matching elements collection
Console.WriteLine(data.First(d => d <= 20)); //result:10 

//try to get first element from matching elements collection else returns default value
Console.WriteLine(data.SingleOrDefault(d => d >= 100)); //result:0, since default value is 0 

//Try to get single element 
// data.Single(); //Exception:Sequence contains more than one element 

//Try to get single element if exist otherwise returns default value
// data.SingleOrDefault(); //Exception:Sequence contains more than one element 

//try to get single element 10 if exist
Console.WriteLine(data.Single(d => d == 10)); //result:10 

//try to get single element 100 if exist otherwise returns default value
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.

    => 두개 이상의 데이터가 존재할 경우 exception 예외처리가 필요하면 Single() 또는 SingleOrDefault() 를 사용하면 됩니다. 


  2. When you want a default value is returned if the result set contains no record, use SingleOrDefault.

    => 검색 결과 데이터가 하나도 없을 경우 기본값을 반환받고자 하면 SingleOrDefault() 를 사용하세요. (FirstOrDefault() 함수와  기능이 동일하지만, 차이점은 SingleOrDefault()는 중복값이 존재하면 Exception 발생)


  3. When you always want one record no matter what the result set contains, use First or FirstOrDefault.

    => 검색 결과 데이터가 있든 없든, 다중값이 존재하든 무조건 하나의 값(레코드)이 필요하다면 First(), FirstOrDefault() 함수를 사용하세요.


  4. When you want a default value if the result set contains no record, use FirstOrDefault.

    => 검색 결과 데이터가 없을때는 기본값을 받고자 할 경우, FirstOrDefault() 함수를 사용하세요.
    (SingleOrDefault() 함수와 기능이 동일하지만, 차이점은 FirstOrDefault() 는 중복값이 존재하면 Exception 을 발생하지 않는다.)

 

 

 

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.

 

=> FirstOrDefault 는 보통 SingleOrDefault와 비교할 때 더 빠릅니다. 이는 첫 번째 일치 항목을 찾을 때까지 컬렉션을 반복하기 때문입니다. 하지만 SingleOrDefault 전체 컬렉션을 반복하여 하나의 일치하는 항목을 찾습니다


더보기

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.