从列表到词典<字符串,字符串>
List<string> listOfAtt = new List<string>();
其中listOfAtt[0] = "FirsName"
,listOfAtt[1] = "Homer"
等
我怎么能创造这种
listOfAtt["FirsName"] = "Homer"
的Dictionary<srting,string>
???
要做到这一点,最好的办法可能是使用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]);
}
'new Dictionary
@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());
尼斯使用'Enumerable.Range' –
非常感谢!但我可能会使用循环) –
所以前两个值是一个关键值对,然后是下两个,yadda yadda ...? – Arran
是的,这就是我想要做的。 –
这里的用例是什么?列表中的值是否唯一?下面的答案都没有考虑到重复,并且将全部失败,例如, “FirsName”在偶数索引处的列表中是两次。 – enzi