text
stringlengths
0
13.4k
//namesById is a Dictionary<int,string>
Console.WriteLine(namesById[3]); //Foo
Console.WriteLine(namesById[4]); //Bar
As stated above, the keys returned by the key selector must be unique. The following will throw an exception.
var persons = new[] {
new { Name="Fizz", Id=1},
new { Name="Buzz", Id=2},
new { Name="Foo", Id=3},
new { Name="Bar", Id=4},
new { Name="Oops", Id=4}
};
var willThrowException = persons.ToDictionary(p => p.Id)
If a unique key can not be given for the source collection, consider using ToLookup instead. On the surface,
ToLookup behaves similarly to ToDictionary, however, in the resulting Lookup each key is paired with a collection of
values with matching keys.
Section 8.40: Union
var numbers1to5 = new[] {1,2,3,4,5};
var numbers4to8 = new[] {4,5,6,7,8};
var numbers1to8 = numbers1to5.Union(numbers4to8);
Console.WriteLine(string.Join(",", numbers1to8));
//1,2,3,4,5,6,7,8
Note that duplicates are removed from the result. If this is undesirable, use Concat instead.
GoalKicker.com – .NET Framework Notes for Professionals
41
Section 8.41: ToArray
var numbers = new[] {1,2,3,4,5,6,7,8,9,10};
var someNumbers = numbers.Where(n => n < 6);
Console.WriteLine(someNumbers.GetType().Name);
//WhereArrayIterator`1
var someNumbersArray = someNumbers.ToArray();
Console.WriteLine(someNumbersArray.GetType().Name);
//Int32[]
Section 8.42: ToList
var numbers = new[] {1,2,3,4,5,6,7,8,9,10};
var someNumbers = numbers.Where(n => n < 6);
Console.WriteLine(someNumbers.GetType().Name);
//WhereArrayIterator`1
var someNumbersList = someNumbers.ToList();
Console.WriteLine(
someNumbersList.GetType().Name + " - " +
someNumbersList.GetType().GetGenericArguments()[0].Name);
//List`1 - Int32
Section 8.43: ElementAt
var names = new[] {"Foo","Bar","Fizz","Buzz"};
var thirdName = names.ElementAt(2);
Console.WriteLine(thirdName); //Fizz
//The following throws ArgumentOutOfRangeException
var minusOnethName = names.ElementAt(-1);
var fifthName = names.ElementAt(4);
Section 8.44: ElementAtOrDefault
var names = new[] {"Foo","Bar","Fizz","Buzz"};
var thirdName = names.ElementAtOrDefault(2);
Console.WriteLine(thirdName); //Fizz
var minusOnethName = names.ElementAtOrDefault(-1);
Console.WriteLine(minusOnethName); //null
var fifthName = names.ElementAtOrDefault(4);
Console.WriteLine(fifthName); //null
Section 8.45: SkipWhile
var numbers = new[] {2,4,6,8,1,3,5,7};
GoalKicker.com – .NET Framework Notes for Professionals
42