我有一个字符串列表,如下所示:
abc|key1|486997
def|key1|488979
ghi|key2|998788
gkl|key2|998778
olz|key1|045669
如何使用LINQ和ToDictionary生成类似于
的Dictionary<string, List<string>>
key1 : { abc|key1|486997, def|key1|488979, olz|key1|045669 }
key2 : { ghi|key2|998788, gkl|key2|998778 }
基本上我希望能够提取第二个元素作为关键字使用ToDictionary()来创建一个字典中的字典。
我现在正在这样做..
var d = new Dictionary<string, List<string>>();
foreach(var l in values)
{
var b = l.Split('|');
var k = b.ElementAtOrDefault(1);
if (!d.ContainsKey(k))
d.Add(k, new List<string>());
d[k].Add(l);
}
我已经看到了从单个分隔值的字符串构建字典的问题,但我是 想知道在开始使用分隔字符串列表时是否有一种优雅的方法。
答案 0 :(得分:4)
var list = new []
{
"abc|key1|486997",
"def|key1|488979",
"ghi|key2|998788",
"gkl|key2|998778",
"olz|key1|045669"
};
var dict = list.GroupBy(x => x.Split('|')[1])
.ToDictionary(x => x.Key, x => x.ToList());
您还可以一次性将其转换为查找(非常类似于Dictionary<K,IEnumerable<V>>
):
var lookup = list.ToLookup(x => x.Split('|')[1]);
答案 1 :(得分:1)
如果您的数据保证一致,那么您可以这样做:
var data = new[]
{
"abc|key1|486997",
"def|key1|488979",
"ghi|key2|998788",
"gkl|key2|998778",
"olz|key1|045669"
};
var items = data
.GroupBy(k => k.Split('|')[1])
.ToDictionary(k => k.Key, v => v.ToList());
答案 2 :(得分:1)
var data = new[]
{
"abc|key1|486997",
"def|key1|488979",
"ghi|key2|998788",
"gkl|key2|998778",
"olz|key1|045669"
};
var dictionary = data.Select(row => row.Split('|'))
.GroupBy(row => row[1])
.ToDictionary(group => group.Key, group => group);