1

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"???

4
  • So the first two values are a key value pair, then the next two, the next two, yadda yadda...? Commented Jul 30, 2013 at 13:44
  • Yes, that's what I want to do. Commented Jul 30, 2013 at 13:45
  • 1
    What is the use case here? Are the values in the list unique? The below answers all do not take duplicates into account and will all fail if e.g. "FirsName" is twice in the list at an even index. Commented Jul 30, 2013 at 13:47
  • The values that should be keys are unique, so those answers I accept=) Commented Jul 30, 2013 at 13:55

3 Answers 3

9

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]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You made a typo twice, srting instead of string ;)
copy and pasted the question I bet ;)
@judgeja probably ^^ I read too fast, i didn't saw it in the question :P
7

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());

2 Comments

Nice use of Enumerable.Range
Thanks a lot! But I'll probably use loop)
2

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]);
}

2 Comments

new Dictionary<string,string> should be new Dictionary<string,string>();, listOfAtt.count should be listOfAtt.Count, and dict.add should be dict.Add.
@Bacon Correct :) I use vb.net primarily so I usually don't worry much about case-sensitivitiy or parentheseis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.