Element Operators
First - SimpleThis sample uses First to return the first matching element as a Product, instead of as a sequence containing a Product. public void Linq58() { List products = GetProductList();
Product product12 = ( from p in products where p.ProductID == 12 select p ) .First();
ObjectDumper.Write(product12); }
Result ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86
First - IndexedThis sample prints the elements of an integer array that are both even and at an even index within the array. It uses First with an index parameter to find the desired numbers. public void Linq60() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int evenNum = numbers.First((num, index) => (num % 2 == 0) && (index % 2 == 0));
Console.WriteLine("{0} is an even number at an even position within the list.", evenNum); }
Result 6 is an even number at an even position within the list.
FirstOrDefault - SimpleThis sample uses FirstOrDefault to try to return the first element of the sequence, unless there are no elements, in which case the default value for that type is returned. public void Linq61() { int[] numbers = {};
int firstNumOrDefault = numbers.FirstOrDefault();
Console.WriteLine(firstNumOrDefault); }
Result 0
FirstOrDefault - ConditionThis sample uses FirstOrDefault to return the first product whose ProductID is 789 as a single Product object, unless there is no match, in which case null is returned. public void Linq62() { List products = GetProductList();
Product product789 = products.FirstOrDefault(p => p.ProductID == 789);
Console.WriteLine("Product 789 exists: {0}", product789 != null); }
Result Product 789 exists: False
FirstOrDefault - IndexedThis sample uses FirstOrDefault to find a number in the array that is within 0.5 of its position in the array, and returns either the first match or the default value of double?, which is null. public void Linq63() { double?[] doubles = { 1.7, 2.3, 4.1, 1.9, 2.9 };
double? num = doubles.FirstOrDefault((n, index) => (n >= index - 0.5 && n <= index + 0.5)); if (num != null) Console.WriteLine("The value {1} is within 0.5 of its index position.", num); else Console.WriteLine("There is no number within 0.5 of its index position.", num); }
Result There is no number within 0.5 of its index position.
ElementAtThis sample prints the fourth number less that 5 in an integer array. The sample first uses a query expression then uses ElementAt to retrieve the fourth number from this sequence. Since ElementAt uses 0-based indexing, 3 is passed to the method to retrieve the fourth element. public void Linq64() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int fourthLowNum = ( from n in numbers where n < 5 select n ) .ElementAt(3); // 3 because sequences use 0-based indexing
Console.WriteLine("Fourth number < 5: {0}", fourthLowNum); }
Result Fourth number < 5: 2 |