The blog has moved to a new address. The blog is now located at http://devintelligence.com

Sunday, January 13, 2008

LINQ to Objects - 3 basic examples

 

The examples below show how you can use aggregate operators in "LINQ to Objects"

// our test data array
string[] names = { "Sara", "Bill", "Alex", "Don", "Tom", "David", "Dana" };

// Find names starts with with character 'D'
int namesStartsWithD = names.Count( name => name.StartsWith("d",
StringComparison.CurrentCultureIgnoreCase ) );
Console.WriteLine("There are {0} names that start with character 'D' in the name list.",
namesStartsWithD);

// Find the longest name
int longestName = names.Max( name=>name.Length );
Console.WriteLine("The longest name is {0} characters long.", longestName);


// Find the first name that starts with character 'D'
string firstStartsWithD = names.First(name => name.StartsWith("d",
StringComparison.CurrentCultureIgnoreCase) );
Console.WriteLine("The first name that start with 'D' - {0}.", firstStartsWithD);



image