简体   繁体   English

LINQ-如何按字典分组 <string, string[]> ?

[英]LINQ - How to Group By with Dictionary <string, string[]>?

I have a dictionary like this: 我有一本这样的字典:

Dictionary<string, string[]> dic = new Dictionary<string,string[]>(){
            {"A", new string [] {"1", "2", "$", "3", "4"}},
            {"B", new string [] {"5", "6", "$", "7", "8"}},
            {"C", new string [] {"9", "10", "@", "11", "12"}}
        };

and I'd like to turn it in to a new Dictionary like this one: 我想把它变成这样的新词典:

Dictionary<string, List<string[]>> res = new Dictionary<string,List<string[]>>{
            {"$", new List<string[]> { 
                new string [] {"1", "2", "A", "3", "4"}, 
                new string [] {"5", "6", "B", "7", "8"} 
                }
            },               
            {"@", new List<string[]> { 
                new string [] {"9", "10", "C", "11", "12"}
                }
            }
        };

so the new Key becomes the 3rd element of the old string array, and the old Key is added to the new string array. 因此新的Key成为旧字符串数组的第3个元素,并将旧的Key添加到新的字符串数组中。

note - the old Key does not need to be placed as the new array's 3rd element, but it does need to be in the same index for each new array. 注意-不需要将旧的Key放置为新数组的第3个元素,但是对于每个新数组,它确实必须位于相同的索引中。

I started trying to use some LINQ for this, but can't wrap my head around the whole thing - this: 我开始尝试为此使用一些LINQ,但是无法将我的头包裹在整个事情上-这是:

Dictionary<string, string[]> test = dic.GroupBy(x => x.Value[2])
.ToDictionary(s => s.Key, s => s.Select(x => x.Key).ToArray());

only works to create another string keyed array valued dictionary where the key's correctly become the 3rd element, but the values are just the old keys. 仅可用于创建另一个字符串键控数组值字典,其中该键正确地变成了第三个元素,但值只是旧键。

One possible solution: 一种可能的解决方案:

Dictionary<string, string[]> dic = new Dictionary<string,string[]>(){
            {"A", new string [] {"1", "2", "$", "3", "4"}},
            {"B", new string [] {"5", "6", "$", "7", "8"}},
            {"C", new string [] {"9", "10", "@", "11", "12"}}
        };

var res = dic.Select(p => new KeyValuePair<string, string[]>(
                              p.Value[2], 
                              p.Value.Select((v,i) => i == 2 ? p.Key : v).ToArray()))
             .GroupBy(p => p.Key)
             .ToDictionary(g => g.Key, g => g.Select(p => p.Value).ToList());
var replacedIndex = 2;

var newDictionary = 
    oldDictionary.GroupBy(x => x.Value.ElementAt(replacedIndex))
                 .ToDictionary(group => group.Key, group => group.Select(x =>
                 {
                     var collection = x.Value;
                     collection[replacedIndex] = x.Key;
                     return collection;
                 }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM