Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the returned values of two selector functions in this code

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.

enter image description here

like image 499
user3467437 Avatar asked Mar 27 '14 14:03

user3467437


1 Answers

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));
like image 160
Eli Arbel Avatar answered Sep 28 '22 04:09

Eli Arbel