简体   繁体   English

从List <string>初始化Dictionary <string,string>

[英]Initialize Dictionary<string,string> from List<string>

Easiest way to do this, perhaps from an extension method? 最简单的方法,也许来自扩展方法? :

var MyDic = new Dictionary<string,string>{ "key1", "val1", "key2", "val2", ...}; 

Where the dictionary winds up with entries contain key and value pairs from the simple list of strings, alternating every other string being the key and values. 当字典结束时,条目包含来自简单字符串列表的键和值对,每隔一个字符串交替作为键和值。

The alternation is a bit of a pain. 交替有点痛苦。 Personally I'd just do it longhand: 就个人而言,我只是做得很简单:

var dictionary = new Dictionary<string, string>();
for (int index = 0; index < list.Count; index += 2)
{
    dictionary[list[index]] = list[index + 1];
}

You definitely can do it with LINQ, but it would be more complicated - I love using LINQ when it makes things simpler, but sometimes it's just not a great fit. 你绝对可以用LINQ做到这一点,但它会更复杂 - 我喜欢使用LINQ,因为它使事情更简单,但有时它不太合适。

(Obviously you can wrap that up into an extension method.) (显然你可以把它包装成一个扩展方法。)

Note that you can use dictionary.Add(list[index], list[index + 1]) to throw an exception if there are duplicate keys - the above code will silently use the last occurrence of a particular key. 请注意,如果存在重复键,则可以使用dictionary.Add(list[index], list[index + 1])抛出异常 - 上面的代码将默默使用特定键的最后一次出现。

You can use a range that is half the length of the list, and ToDictionary to create the dictionary from items from the list: 您可以使用列表长度的一半的范围,并使用ToDictionary从列表中的项目创建字典:

Dictionary<string, string> dictionary =
  Enumerable.Range(0, list.Count / 2)
  .ToDictionary(i => list[i * 2], i => list[i * 2 + 1]);

LINQ and GroupBy version: LINQ和GroupBy版本:

var dict = source.Select((s, i) => new { s, i })
                 .GroupBy(x => x.i / 2)
                 .ToDictionary(g => g.First().s, g => g.Last().s);

If you need LINQ - you can Zip list to itself first: 如果您需要LINQ - 您可以先将Zip列表发送给自己:

var result = list.Where((item, id) => id % 2 == 0)
     .Zip (list.Where((item, id) => id % 2 == 1), 
          (key, value) => new KeyValuePair<string,string>(key, value))
     .ToDictionary(p => p.Key, p => p.Value);

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

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