Part of the 101 LINQ SAMPLES
Learn how to use LINQ in your applications with these code samples, covering the entire range of LINQ functionality and demonstrating LINQ with SQL, DataSets, and XML.

Introduction

 This sample shows different uses of Element Operators:

Building the Sample

  1. Open the Program.cs
  2. Comment or uncomment the desired samples
  3. Press Ctrl + F5

Description

First - Simple

(back to top)

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

C#
Edit|Remove
public void Linq58() 
{ 
    List<Product> 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 - Condition

(back to top)

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

C#
Edit|Remove
public void Linq59() 
{ 
    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); 
}

Result

A string starting with 'o': one

 

FirstOrDefault - Simple

(back to top)

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.

C#
Edit|Remove
public void Linq61() 
  
{ 
    int[] numbers = { }; 
  
    int firstNumOrDefault = numbers.FirstOrDefault(); 
  
    Console.WriteLine(firstNumOrDefault); 
}

Result

0

 

FirstOrDefault - Condition

(back to top)

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.

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

Result

Product 789 exists: False

 

ElementAt

(back to top)

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

C#
Edit|Remove
public void Linq64() 
{ 
    int[] numbers = { 5413986720 }; 
  
    int fourthLowNum = ( 
        from n in numbers 
        where n > 5 
        select n) 
        .ElementAt(1);  // second number is index 1 because sequences use 0-based indexing 
 
    Console.WriteLine("Second number > 5: {0}", fourthLowNum); 
}
 Result

Second number > 5: 8

 

Source Code Files

101 LINQ Samples

More Information

For more information, see: