Sashko  Chehotsky
Sashko Chehotsky

Reputation: 408

From List<string> to Dictionary<string,string>

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

Answers (3)

Dan Drews
Dan Drews

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

lc.
lc.

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

Mehmet Ataş
Mehmet Ataş

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

Related Questions