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"???
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"???
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]);
}
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());
Enumerable.RangeThe 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]);
}
new Dictionary<string,string> should be new Dictionary<string,string>();, listOfAtt.count should be listOfAtt.Count, and dict.add should be dict.Add.