Element Operators (LINQ)
Posted by Rajinder
Last Updated: July 23, 2012
  1434

First

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

public void Linq() 
{ 
    List<Product> products = GetProductList(); 
 
    Product product12 = ( 
        from p in products 
        where p.ProductID == 12 
        select p) 
        .First(); 
  
    ObjectDumper.Write(product12); 
}

First - Condition

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

public void Linq() 
{ 
    string[] strings = { "zero""one""two""three""four""five""six""seven""eight""nine" }; 
  
    string startsWithO = strings.First(s => s[0] == 'o'); 
  
    Console.WriteLine("A string starting with 'o': {0}", startsWithO); 
}

FirstOrDefault

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.

public void Linq() 
  
{ 
    int[] numbers = { }; 
  
    int firstNumOrDefault = numbers.FirstOrDefault(); 
  
    Console.WriteLine(firstNumOrDefault); 
}

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.

public void Linq() 
{ 
    List<Product> products = GetProductList(); 
  
    Product product789 = products.FirstOrDefault(p => p.ProductID == 789); 
 
    Console.WriteLine("Product 789 exists: {0}", product789 != null); 
}