Reputation: 408
I have List
List<string> listOfAtt = new List<string>();
where listOfAtt[0] = "FirsName"
, listOfAtt[1] = "Homer"
etc.
How can I create a Dictionary<srting,string>
of this kind
listOfAtt["FirsName"] = "Homer"
???
Upvotes: 1
Views: 208
Reputation: 1976
The best way to do this is probably using a for loop
Dictionary<string,string> dict = new Dictionary<string,string>();
for (int i = 0; i < listOfAtt.Count; i+=2){
dict.Add(listOfAtt[i], listOfAtt[i+1]);
}
Upvotes: 2
Reputation: 116538
Assuming uniqueness of keys, a LINQ-y way to do it would be:
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:
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());
Upvotes: 7
Reputation: 11559
Assuming listOfAtt.Count
is even and items at even indices are unique you can do below.
Dictionary<string,string> dic = new Dictionary<string,string>();
for (int i = 0; i < listOfAtt.Count; i+=2) {
dic.Add(listOfAtt[i], listOfAtt[i + 1]);
}
Upvotes: 9