101 LINQ Samples: Element Operators

First - Simple

This sample uses First to return the first matching element as a Product, instead of as a sequence containing a Product.

  1. public void Linq58()
  2.  
  3. {
  4.  
  5.     List<Product> products = GetProductList();
  6.  
  7.  
  8.  
  9.     Product product12 = (
  10.  
  11.         from p in products
  12.  
  13.         where p.ProductID == 12
  14.  
  15.         select p)
  16.  
  17.         .First();
  18.  
  19.  
  20.  
  21.     ObjectDumper.Write(product12);
  22.  
  23. }

Result

ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86

First - Condition

This sample uses First to find the first element in the array that starts with 'o'.


  1. public void Linq59()
  2.  
  3. {
  4.  
  5.     string[] strings = { "zero""one""two""three""four""five""six""seven""eight""nine" };
  6.  
  7.  
  8.  
  9.     string startsWithO = strings.First(s => s[0] == 'o');
  10.  
  11.  
  12.  
  13.     Console.WriteLine("A string starting with 'o': {0}", startsWithO);
  14.  
  15. }

Result

A string starting with 'o': one

FirstOrDefault - Simple

This 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.

  1. public void Linq61()
  2.  
  3. {
  4.  
  5.     int[] numbers = { };
  6.  
  7.  
  8.  
  9.     int firstNumOrDefault = numbers.FirstOrDefault();
  10.  
  11.  
  12.  
  13.     Console.WriteLine(firstNumOrDefault);
  14.  
  15. }

Result

0

FirstOrDefault - Condition

This 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.

  1. public void Linq62()
  2.  
  3. {
  4.  
  5.     List<Product> products = GetProductList();
  6.  
  7.  
  8.  
  9.     Product product789 = products.FirstOrDefault(p => p.ProductID == 789);
  10.  
  11.  
  12.  
  13.     Console.WriteLine("Product 789 exists: {0}", product789 != null);
  14.  
  15. }

Result

Product 789 exists: False

ElementAt

This sample uses ElementAt to retrieve the second number greater than 5 from an array.

  1. public void Linq64()
  2.  
  3. {
  4.  
  5.     int[] numbers = { 5413986720 };
  6.  
  7.  
  8.  
  9.     int fourthLowNum = (
  10.  
  11.         from n in numbers
  12.  
  13.         where n > 5
  14.  
  15.         select n)
  16.  
  17.         .ElementAt(1);  // second number is index 1 because sequences use 0-based indexing
  18.  
  19.  
  20.  
  21.     Console.WriteLine("Second number > 5: {0}", fourthLowNum);
  22.  
  23. }

Result

Second number > 5: 8

posted @ 2011-03-13 20:15  i'm zjz  阅读(184)  评论(0编辑  收藏  举报