.First를 언제 사용하고 .FirstOrDefault를 LINQ와 함께 사용합니까?
주변을 검색했지만 언제 .First
사용 .FirstOrDefault
하고 LINQ와 함께 사용하고 싶은지에 대한 명확한 답을 찾지 못했습니다 .
언제 사용
.First
하시겠습니까? 반환 된 결과가없는 경우 예외를 포착하고 싶을 때만?var result = List.Where(x => x == "foo").First();
그리고 언제 사용하고 싶
.FirstOrDefault
습니까? 결과가 없으면 항상 기본 유형을 원하십니까?var result = List.Where(x => x == "foo").FirstOrDefault();
그리고 그 문제에 대해 Take는 어떻습니까?
var result = List.Where(x => x == "foo").Take(1);
First()
시퀀스에 적어도 하나의 요소가있을 것을 알고 있거나 기대할 때 사용 합니다. 즉, 예외적 인 경우 시퀀스가 비어있는 경우입니다.
FirstOrDefault()
요소가 있는지 여부를 확인해야 할 때 사용하십시오 . 즉, 시퀀스가 비어있는 것이 합법적 일 때. 검사를 위해 예외 처리에 의존해서는 안됩니다. (나쁜 습관이며 성능을 떨어 뜨릴 수 있습니다).
마지막으로, 차이 First()
및 Take(1)
즉 First()
복귀하면서 소자 자체가 Take(1)
정확히 하나 개의 원소를 함유 원소의 복귀 시퀀스.
.First
결과가 없으면 예외가 발생합니다. .FirstOrDefault
그렇지 않으면 단순히 null (참조 유형) 또는 값 유형의 기본값을 반환합니다. (예 : 0
int 와 같은 ) 여기서 질문은 기본 유형을 원할 때가 아니라 더 많은 것입니다. 예외를 처리하거나 기본값을 처리 할 의향이 있습니까? 예외는 예외적이어야하므로 FirstOrDefault
쿼리에서 결과를 얻을 수 있을지 확실하지 않을 때는 선호됩니다. 논리적으로 데이터가 있어야하는 경우 예외 처리를 고려할 수 있습니다.
Skip()
및 Take()
결과에 페이징을 설정할 때 일반적으로 사용된다. (처음 10 개의 결과를 표시하고 다음 페이지에 다음 10 개를 표시하는 것과 같습니다.)
도움이 되었기를 바랍니다.
.First()
반환 할 행이 없으면 예외를 throw하고 대신 .FirstOrDefault()
기본값 ( NULL
모든 참조 유형에 대해)을 반환합니다 .
따라서 준비가되어 있고 가능한 예외를 처리 할 의향이 있다면 .First()
괜찮습니다. != null
어쨌든 반환 값을 확인하려면 .FirstOrDefault()
더 나은 선택입니다.
그러나 나는 그것이 약간의 개인적인 선호도라고 생각합니다. 자신에게 더 의미 있고 코딩 스타일에 더 잘 맞는 것을 사용하십시오.
먼저()
- 시퀀스의 첫 번째 요소를 반환합니다.
- 결과에 요소가 없거나 소스가 null 인 경우 오류가 발생합니다.
- 두 개 이상의 요소가 예상되고 첫 번째 요소 만 원하는 경우 사용해야합니다.
FirstOrDefault ()
- 시퀀스의 첫 번째 요소를 반환하거나 요소가없는 경우 기본값을 반환합니다.
- 소스가 null 인 경우에만 오류가 발생합니다.
- 두 개 이상의 요소가 예상되고 첫 번째 요소 만 원하는 경우 사용해야합니다. 결과가 비어 있으면 좋습니다.
아래와 같이 일부 레코드가있는 UserInfos 테이블이 있습니다. 아래 표를 기반으로 예제를 만들었습니다.
First () 사용 방법
var result = dc.UserInfos.First(x => x.ID == 1);
ID == 1 인 레코드는 하나뿐입니다.이 레코드를 반환해야합니다
. ID : 1 이름 : Manish 성 : Dubey 이메일 : xyz@xyz.com
var result = dc.UserInfos.First(x => x.FName == "Rahul");
FName == "Rahul"인 레코드가 여러 개 있습니다. 첫 번째 기록은 반환되어야합니다.
ID : 7 이름 : Rahul 성 : Sharma 이메일 : xyz1@xyz.com
var result = dc.UserInfos.First(x => x.ID ==13);
ID == 13 인 레코드가 없습니다. 오류가 발생해야합니다.
InvalidOperationException : 시퀀스에 요소가 없습니다.
FirstOrDefault () 사용 방법
var result = dc.UserInfos.FirstOrDefault(x => x.ID == 1);
ID == 1 인 레코드는 하나뿐입니다.이 레코드를 반환해야합니다
. ID : 1 이름 : Manish 성 : Dubey 이메일 : xyz@xyz.com
var result = dc.UserInfos.FirstOrDefault(x => x.FName == "Rahul");
FName == "Rahul"인 레코드가 여러 개 있습니다. 첫 번째 기록은 반환되어야합니다.
ID : 7 이름 : Rahul 성 : Sharma 이메일 : xyz1@xyz.com
var result = dc.UserInfos.FirstOrDefault(x => x.ID ==13);
ID == 13 인 레코드가 없습니다. 반환 값은 null입니다.
Hope it will help you to understand when to use First()
or FirstOrDefault()
.
First of all, Take
is a completely different method. It returns an IEnumerable<T>
and not a single T
, so that's out.
Between First
and FirstOrDefault
, you should use First
when you're sure that an element exists and if it doesn't, then there's an error.
By the way, if your sequence contains default(T)
elements (e.g. null
) and you need to distinguish between being empty and the first element being null
, you can't use FirstOrDefault
.
First:
- Returns the first element of a sequence
- Throws exception: There are no elements in the result
- Use when: When more than 1 element is expected and you want only the first
FirstOrDefault:
- Returns the first element of a sequence, or a default value if no element is found
- Throws exception: Only if the source is null
- Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty
From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
Another difference to note is that if you're debugging an application in a Production environment you might not have access to line numbers, so identifying which particular .First()
statement in a method threw the exception may be difficult.
The exception message will also not include any Lambda expressions you might have used which would make any problem even are harder to debug.
That's why I always use FirstOrDefault()
even though I know a null entry would constitute an exceptional situation.
var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
if (customer == null)
{
throw new Exception(string.Format("Can't find customer {0}.", customerId));
}
First()
When you know that result contain more than 1 element expected and you should only the first element of sequence.
FirstOrDefault()
FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.
I found a website that apperars to explain the need for FirstOrDefault
http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
If there are no results to a query, and you want to to call First() or Single() to get a single row... You will get an “Sequence contains no elements” exception.
Disclaimer: I have never used LINQ, so my apologies if this is way off the mark.
This type of the function belongs to element operators. Some useful element operators are defined below.
- First/FirstOrDefault
- Last/LastOrDefault
- Single/SingleOrDefault
We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.
List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };
First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.
int result = items.Where(item => item == 2).First();
FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.
int result1 = items.Where(item => item == 2).FirstOrDefault();
someList.First(); // exception if collection is empty.
someList.FirstOrDefault(); // first item or default(Type)
Which one to use? It should be decided by the business logic, and not the fear of exception/programm failure.
For instance, If business logic says that we can not have zero transactions on any working day (Just assume). Then you should not try to handle this scenario with some smart programming. I will always use First() over such collection, and let the program fail if something else screwed up the business logic.
Code:
var transactionsOnWorkingDay = GetTransactionOnLatestWorkingDay();
var justNeedOneToProcess = transactionsOnWorkingDay.First(): //Not FirstOrDefault()
I would like to see others comments over this.
Ok let me give my two cents. First / Firstordefault are for when you use the second constructor. I won't explain what it is, but it's when you would potentially always use one because you don't want to cause an exception.
person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
{
return string.IsNullOrEmpty(p.Relationship);
}));
linq many ways to implement single simple query on collections, just we write joins in sql, a filter can be applied first or last depending on the need and necessity.
다음은 컬렉션에서 ID가있는 요소를 찾을 수있는 예입니다. 이것에 대해 더 추가하기 위해, 메소드 First, FirstOrDefault
는 이상적으로 컬렉션에 최소한 하나의 레코드가있을 때 동일한 결과를 반환합니다. 그러나 컬렉션이 비어 있어도 괜찮습니다. 그러면 First
예외 FirstOrDefault
가 반환 되지만 반환 null
되거나 기본값이됩니다. 예를 들어, int
는 0을 반환합니다. 따라서 이러한 사용은 개인적인 선호라고 말하지만 FirstOrDefault
예외 처리를 피하기 위해 사용 하는 것이 좋습니다 .
'program tip' 카테고리의 다른 글
Java에 파일이 있는지 어떻게 확인합니까? (0) | 2020.09.29 |
---|---|
문자를 문자열로 변환하는 방법? (0) | 2020.09.29 |
중첩 된 객체, 배열 또는 JSON에 액세스하고 처리하려면 어떻게해야합니까? (0) | 2020.09.29 |
셸 명령 실행 및 출력 캡처 (0) | 2020.09.29 |
이름으로 데이터 프레임 열 삭제 (0) | 2020.09.29 |