using System;
using System.Collections.Generic;
using System.Linq; namespace Linq101
{
class Element
{
/// <summary>
/// This sample uses First to return the first matching element as a Product, instead of as a sequence containing a Product.
/// </summary>
public void Linq58()
{
List<Data.Product> products = Data.GetProductList(); Data.Product product12 = (from p in products
where p.ProductID ==
select p).First(); ObjectDumper.Write(product12);
} /// <summary>
/// This sample uses First to find the first element in the array that starts with 'o'.
/// </summary>
public void Linq59()
{
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string startsWithO = strings.First(s => s[] == 'o'); Console.WriteLine("A string starting with 'o': {0}", startsWithO);
} /// <summary>
/// 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.
/// </summary>
public void Linq60()
{
int[] numbers = { }; int firstNumOrDefault = numbers.FirstOrDefault(); Console.WriteLine(firstNumOrDefault);
} /// <summary>
/// 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.
/// </summary>
public void Linq61()
{
List<Data.Product> products = Data.GetProductList(); Data.Product product789 = products.FirstOrDefault(p => p.ProductID == ); Console.WriteLine("Product 789 exists: {0}", product789 != null);
} /// <summary>
/// This sample uses ElementAt to retrieve the second number greater than 5 from an array.
/// </summary>
public void Linq62()
{
int[] numbers = { , , , , , , , , , }; int number = (from n in numbers
where n >
select n).ElementAt(); Console.WriteLine("Second number > 5: {0}", number);
}
}
}