5
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));

Students对象具有NameWeight键值对。

在 ToDictionary 方法中,t变量的类型为IEnumerable<IGrouping<K, T>>。那是,IEnumerable<IGrouping<int, Students>>

为什么返回的值Key不同?它们都使用相同的变量。应该是类型。t=>t.Keyt=> t.Select(**x=> x.Key**)tKeyint

该图像是在执行 GroupBy 方法后拍摄的。(它不是完整图像)其中一个Key具有 的值,另一个60具有 和 的值。BobMattAdam

在此处输入图像描述

4

4 回答 4

2

因为它不是一个

IEnumerable<IGrouping<int, Student>>

它是

IEnumerable<IGrouping<int, KeyValuePair<int, Student>>>

t => t.Key你指的是分组键,在Select(x => x.Key)你指的是KeyValuePair.

您可以将鼠标悬停在 Visual Studio 中的变量上以查看类型和类型参数。

更详细地说:

// 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));
于 2014-03-27T14:51:08.093 回答
2

它正在创建一个以数字为键的新字典,以及与特定键相关的原始字典中的所有学生姓名。

下面是它的工作原理。

为什么返回的键值是t=>t.Key

那是在原始字典中的GroupBy,GroupBy上进行操作。因此,新字典将具有基于原始字典值的不同键。Valueint

和 t=> t.Select( x=> x.Key ) 不同吗?

现在这是对原始字典Select中的每个项目进行操作。学生姓名GroupBy在哪里。Key从而根据Key之前选择的内容获取所有学生姓名GroupBy

于 2014-03-27T14:51:14.147 回答
1

这就是结果的Students.GroupBy(r => r.Value)样子。这有点令人困惑,因为两者GroupByDictionary使用Key.

    { (Key = 60, {(Key = "Bob", Value = 60), (Key = "Matt", Value = 60), ...}),
      (Key = 62, {(Key = "Jim", Value = 62)}),
      (Key = 72. ...),
      ...
    }

t是该分组的一行

第一个选择器t.Key产生60.

第二个选择器t.Select(x => x.Key)列表进行操作并产生{"Bob", "Matt", "Adam"}

于 2014-03-27T14:50:23.330 回答
0

Key( IGrouping)的t.Key是您在 中分组的键GroupBy。在这种情况下,这是ValueKeyValuePair

Select( x.Key) 中的密钥正在获取组KeyValuePair内每一对的密钥。

由于推断的类型,这里不太明显,但您可以将鼠标悬停在两者上x,并t在视觉工作室中查看它t是 anIGroupingx是 a KeyValuePair。您还可以通过使用更有意义的变量名称来提高此查询的清晰度(在我看来是相当多的)。

var MyVar = Students.GroupBy(pair => pair.Value)
                        .ToDictionary(group => group.Key,
                        group => group.Select(pair => pair.Key));
于 2014-03-27T14:48:45.437 回答