Retrieving only the first record or record at a certain index in LINQ
Posted
by vik20000in
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by vik20000in
Published on Fri, 16 Apr 2010 06:30:00 GMT
Indexed on
2010/04/16
6:33 UTC
Read the original article
Hit count: 628
While working with data it’s not always required that we fetch all the records. Many a times we only need to fetch the first record, or some records in some index, in the record set. With LINQ we can get the desired record very easily with the help of the provided element operators.
Simple get the first record.
If you want only the first record in record set we can use the first method [Note that this can also be done easily done with the help of the take method by providing the value as one].
List<Product> products = GetProductList();
Product product12 = (
from prod in products
where prod.ProductID == 12
select prod)
.First();
We can also very easily put some condition on which first record to be fetched.
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string startsWithO = strings.First(s => s[0] == 'o');
In the above example the result would be “one” because that is the first record starting with “o”.
Also the fact that there will be chances that there are no value returned in the result set. When we know such possibilities we can use the FirstorDefault() method to return the first record or incase there are no records get the default value.
int[] numbers = {};
int firstNumOrDefault = numbers.FirstOrDefault();
In case we do not want the first record but the second or the third or any other later record then we can use the ElementAt() method. In the ElementAt() method we need to pass the index number for which we want the record and we will receive the result for that element.
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int fourthLowNum = (
from num in numbers
where num > 5
select num )
.ElementAt(1);
Vikram
© ASP.net Weblogs or respective owner