text stringlengths 0 13.4k |
|---|
This method calculates the average of enumerable of numbers. |
var cities = new[] { |
GoalKicker.com – .NET Framework Notes for Professionals |
39 |
new {Population = 1000}, |
new {Population = 2000}, |
new {Population = 4000} |
}; |
var averagePopulation = cities.Average(c => c.Population); |
Console.WriteLine(averagePopulation); |
// 2333,33 |
This method calculates the average of enumerable using delegated function. |
Section 8.38: GroupBy |
var persons = new[] { |
new { Name="Fizz", Job="Developer"}, |
new { Name="Buzz", Job="Developer"}, |
new { Name="Foo", Job="Astronaut"}, |
new { Name="Bar", Job="Astronaut"}, |
}; |
var groupedByJob = persons.GroupBy(p => p.Job); |
foreach(var theGroup in groupedByJob) |
{ |
Console.WriteLine( |
"{0} are {1}s", |
string.Join(",", theGroup.Select(g => g.Name).ToArray()), |
theGroup.Key); |
} |
//Fizz,Buzz are Developers |
//Foo,Bar are Astronauts |
Group invoices by country, generating a new object with the number of record, total paid, and average paid |
var a = db.Invoices.GroupBy(i => i.Country) |
.Select(g => new { Country = g.Key, |
Count = g.Count(), |
Total = g.Sum(i => i.Paid), |
Average = g.Average(i => i.Paid) }); |
If we want only the totals, no group |
var a = db.Invoices.GroupBy(i => 1) |
.Select(g => new { Count = g.Count(), |
Total = g.Sum(i => i.Paid), |
Average = g.Average(i => i.Paid) }); |
If we need several counts |
var a = db.Invoices.GroupBy(g => 1) |
.Select(g => new { High = g.Count(i => i.Paid >= 1000), |
Low = g.Count(i => i.Paid < 1000), |
Sum = g.Sum(i => i.Paid) }); |
Section 8.39: ToDictionary |
Returns a new dictionary from the source IEnumerable using the provided keySelector function to determine keys. |
GoalKicker.com – .NET Framework Notes for Professionals |
40 |
Will throw an ArgumentException if keySelector is not injective(returns a unique value for each member of the |
source collection.) There are overloads which allow one to specify the value to be stored as well as the key. |
var persons = new[] { |
new { Name="Fizz", Id=1}, |
new { Name="Buzz", Id=2}, |
new { Name="Foo", Id=3}, |
new { Name="Bar", Id=4}, |
}; |
Specifying just a key selector function will create a Dictionary<TKey,TVal> with TKey the return Type of the key |
selector, TVal the original object Type, and the original object as the stored value. |
var personsById = persons.ToDictionary(p => p.Id); |
// personsById is a Dictionary<int,object> |
Console.WriteLine(personsById[1].Name); //Fizz |
Console.WriteLine(personsById[2].Name); //Buzz |
Specifying a value selector function as well will create a Dictionary<TKey,TVal> with TKey still the return type of |
the key selector, but TVal now the return type of the value selector function, and the returned value as the stored |
value. |
var namesById = persons.ToDictionary(p => p.Id, p => p.Name); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.