从列表到词典<字符串,字符串>

问题描述:

我有列表从列表<string>到词典<字符串,字符串>

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

其中listOfAtt[0] = "FirsName"listOfAtt[1] = "Homer"

我怎么能创造这种

listOfAtt["FirsName"] = "Homer"Dictionary<srting,string> ???

+0

所以前两个值是一个关键值对,然后是下两个,yadda yadda ...? – Arran

+0

是的,这就是我想要做的。 –

+1

这里的用例是什么?列表中的值是否唯一?下面的答案都没有考虑到重复,并且将全部失败,例如, “FirsName”在偶数索引处的列表中是两次。 – enzi

假设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]); 
} 
+2

你犯了一个错字两次,srting而不是字符串;) – dotixx

+0

复制并粘贴我打赌的问题;) – James

+0

是的,当然我做过(: –

要做到这一点,最好的办法可能是使用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]); 
} 
+1

'new Dictionary '应该是'new Dictionary ();','listOfAtt.count'应该是'listOfAtt.Count','dict.add'应该是'dict.Add'。 – BACON

+0

@Bacon正确:)我主要使用vb.net,所以我通常不太担心大小写敏感或parentheseis –

假设键的唯一性,一个LINQ-Y的方式做这将是:

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

如果事情并不是那么独特,你可以扩展这个逻辑,按键组返回一个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()); 
+1

尼斯使用'Enumerable.Range' –

+0

非常感谢!但我可能会使用循环) –