グループ化(ToLookup、GroupBy) [Programming]
スポンサーリンク
[C# サンプルソース]
・Dictionary の値によるグループ化
Dictionary<string, int> data = new Dictionary<string, int>() { { "key1", 10 }, { "key2", 20 }, { "key3", 10 } }; var groupLookup = data.ToLookup(x => x.Value); // ILookup<int, KeyValuePair<string, int>> groupLookup = data.ToLookup(x => x.Value); var groupGroupby = data.GroupBy(x => x.Value); // IEnumerable<IGrouping<int, KeyValuePair<string, int>>> groupGroupby = data.GroupBy(x => x.Value); // ToLookup 結果表示 Array.ForEach(groupLookup.ToArray(), x => Array.ForEach(x.ToArray(), y => System.Diagnostics.Debug.WriteLine($"Group : {x.Key}, Key : {y.Key}, Value : {y.Value}"))); // GroupBy 結果表示 Array.ForEach(groupGroupby.ToArray(), x => Array.ForEach(x.ToArray(), y => System.Diagnostics.Debug.WriteLine($"Group : {x.Key}, Key : {y.Key}, Value : {y.Value}"))); // lookup 結果表示 Array.ForEach(groupLookup[10].ToArray(), x => System.Diagnostics.Debug.WriteLine($"Group : 10, Key : {x.Key}, Value : {x.Value}")); Array.ForEach(groupLookup[20].ToArray(), x => System.Diagnostics.Debug.WriteLine($"Group : 20, Key : {x.Key}, Value : {x.Value}"));
[ToLookup 結果表示]
Group : 10, Key : key1, Value : 10 Group : 10, Key : key3, Value : 10 Group : 20, Key : key2, Value : 20
[GroupBy 結果表示]
Group : 10, Key : key1, Value : 10 Group : 10, Key : key3, Value : 10 Group : 20, Key : key2, Value : 20
[lookup 結果表示]
Group : 10, Key : key1, Value : 10 Group : 10, Key : key3, Value : 10 Group : 20, Key : key2, Value : 20
・GroupBy() : 遅延評価、 ToLookup() : 即時評価
スポンサーリンク
コメント 0