将逗号分隔值转换为字典

时间:2014-08-05 23:47:49

标签: c# asp.net linq

我正在尝试将逗号分隔的字符串转换为字典

string text = "abc,xyz,pqr";

输出应为Dictionary<string, uint>,密钥为来自text&amp;的字符串。值从0开始。

我在下面试过,但它给出了错误:

text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToDictionary(split => split[0], 0))`

我也不确定如何提供增量值,所以我尝试使用常量硬编码值来处理字典中的所有键,如上所示,但它也给出错误。

对所有键的常量值或使用linq的增量值的任何帮助都非常有用!!

2 个答案:

答案 0 :(得分:7)

Select()的重载传递索引:

var dict = text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
    .Select((str, idx) => new { str, idx })
    .ToDictionary(x => x.str, x => x.idx);

答案 1 :(得分:0)

逗号分隔值字符串中是否存在重复的可能性?如果是这样,输出到Dictionary会使您容易受到异常的影响:

An item with the same key has already been added.

如果重复 有可能,那么您可以考虑输出Lookup<TKey, TElement>作为替代:

  

Lookup<TKey, TElement>类似于Dictionary<TKey, TValue>。区别在于Dictionary<TKey, TValue>   将键映射到单个值,而Lookup<TKey, TElement>映射   价值集合的关键。

这是一个与the answer by @Corey Nelson类似的解决方案,它利用ToLookup()生成Lookup

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string text = "abc,xyz,pqr,linq,xyz,abc,is,xyz,pqr,fun";

        var lookup =
            text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
            .Select((str, idx) => new { str, idx })
            .ToLookup(x => x.str, x => (uint)x.idx);

        foreach (IGrouping<string, uint> itemGroup in lookup)
        {
            Console.WriteLine("Item '{0}' appears at:", itemGroup.Key);

            foreach (uint item in itemGroup)
            {
                Console.WriteLine("- {0}", item);
            }
        }
    }
}

预期输出:

Item 'abc' appears at:
- 0
- 5
Item 'xyz' appears at:
- 1
- 4
- 7
Item 'pqr' appears at:
- 2
- 8
Item 'linq' appears at:
- 3
Item 'is' appears at:
- 6
Item 'fun' appears at:
- 9
相关问题