c# - 使用 LINQ 从分隔字符串列表构建字典

标签 c# linq dictionary

我有一个字符串列表,如下所示:

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

我看过有关从单个分隔值字符串构建字典的问题,但我 想知道在从分隔字符串列表开始时是否有一种优雅的方法来执行此操作。

最佳答案

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

关于c# - 使用 LINQ 从分隔字符串列表构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10436767/

相关文章:

c# - .NET Core/EF Core 2.0 升级后急切加载 "No coercion operator is defined between types"

python - 将项目添加到列表字典

c# - C#中的骨架化OpenCV

c# - 基于计数的 orderby 相关性的 LINQ 关键字搜索 (LINQ to SQL)

c# - 在编译时获取非静态方法的 MethodInfo

Python-字典状态和资本游戏

python - 将元组转换为字典

c# - 如何从文本文件中获取 2 个数据点

c# - 文件被复制到 SysWOW64 而不是 System32

c# - GroupBy 和 IEqualityComparer<TKey> 比较器