- When would you want to use
.First
? Only when you'd want to catch the exception if no results where returned?
var result = List.Where(x => x == "foo").First();
- And when would you want to use
.FirstOrDefault
? When you'd always want the default type if no result?
var result = List.Where(x => x == "foo").FirstOrDefault();
- And for that matter, what about Take?
var result = List.Where(x => x == "foo").Take(1);
I would useFirst()
when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence when the sequence is empty.
UseFirstOrDefault()
when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).
Finally, the difference betweenFirst()
andTake()
is thatFirst()
returns the element itself, whileTake()
returns a sequence of elements that contains exactly one element. (If you pass 1 as the parameter).
Thứ Năm, 12 tháng 6, 2014
Cách lấy phần tử đầu tiên Linq C#
Đăng ký:
Đăng Nhận xét (Atom)
Không có nhận xét nào:
Đăng nhận xét