var Students = new Dictionary<string, int>();
Students.Add( "Bob" , 60);
Students.Add( "Jim" , 62);
Students.Add( "Jack", 75);
Students.Add( "John", 81);
Students.Add( "Matt", 60);
Students.Add( "Jill", 72);
Students.Add( "Eric", 83);
Students.Add( "Adam", 60);
Students.Add( "Gary", 75);
var MyVar = Students.GroupBy(r=> r.Value)
.ToDictionary(t=> t.Key, t=> t.Select(x=> x.Key));
The Students
object has Name
and Weight
key-value pairs.
In the ToDictionary method, t
variable is of type IEnumerable<IGrouping<K, T>>
. That is, IEnumerable<IGrouping<int, Students>>
Why are the Key
values returned by t=>t.Key
and t=> t.Select(**x=> x.Key**)
different? They both use the same t
variable. Key
should be of type int
.
The image was taken after the GroupBy method had been executed.(It is not the full image) One of the Key
has the value of 60
and the other one has the values of Bob
, Matt
and Adam
.
Because it's not a
IEnumerable<IGrouping<int, Student>>
It's a
IEnumerable<IGrouping<int, KeyValuePair<int, Student>>>
In t => t.Key
you're referring to the grouping key, and in Select(x => x.Key)
you're referring to the KeyValuePair
.
You can hover over the variables in Visual Studio to see the types and the type parameters.
In more detail:
// return an IEnumerable<IGrouping<int, KeyValuePair<int, Student>>>
Students.GroupBy(r=> r.Value)
// iterate over each IGrouping<int, KeyValuePair<int, Student>>
.ToDictionary(
group => group.Key,
// iterate over each KeyValuePair<int, Student> in the group
// because IGrouping<TKey, TElement> inherits from IEnumerable<TElement>
// so it's a Select over an IEnumerable<KeyValuePair<int, Student>>
group => group.Select(pair => pair.Key));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With