简体   繁体   English

从清单 <string> 到字典 <string,string>

[英]From List<string> to Dictionary<string,string>

I have List 我有清单

List<string> listOfAtt = new List<string>();

where listOfAtt[0] = "FirsName" , listOfAtt[1] = "Homer" etc. 其中listOfAtt[0] = "FirsName"listOfAtt[1] = "Homer"等。

How can I create a Dictionary<srting,string> of this kind 如何创建这种Dictionary<srting,string>

listOfAtt["FirsName"] = "Homer" ??? listOfAtt["FirsName"] = "Homer" ???

Assuming listOfAtt.Count is even and items at even indices are unique you can do below. 假设listOfAtt.Count是偶数,并且偶数索引处的项是唯一的,则可以在下面执行。

Dictionary<string,string> dic = new Dictionary<string,string>();

for (int i = 0; i < listOfAtt.Count; i+=2) {
    dic.Add(listOfAtt[i], listOfAtt[i + 1]);
}

Assuming uniqueness of keys, a LINQ-y way to do it would be: 假设密钥是唯一的,则LINQ-y的实现方法是:

Enumerable.Range(0, listOfAtt.Count / 2)
          .ToDictionary(x => listOfAtt[2 * x], x => listOfAtt[2 * x + 1]);

If things are not so unique, you could extend this logic, group by key and return a Dictionary<string, List<string>> like: 如果事情不是那么独特,则可以扩展此逻辑,按键分组并返回Dictionary<string, List<string>>例如:

Enumerable.Range(0, listOfAtt.Count / 2)
          .Select(i => new { Key = listOfAtt[2 * i], Value = listOfAtt[2*i+1] })
          .GroupBy(x => x.Key)
          .ToDictionary(x => x.Key, x => x.Select(X => X.Value).ToList());

The best way to do this is probably using a for loop 最好的方法可能是使用for循环

Dictionary<string,string> dict = new Dictionary<string,string>();

for (int i = 0; i < listOfAtt.Count; i+=2){
    dict.Add(listOfAtt[i], listOfAtt[i+1]);
}

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

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