1

I have an array of strings. Each string is two numbers separated with a "|".

How can I get this array of string into Dictionary<int,int> without looping through the array, splitting each string and adding to the dictionary.

Is there a better way?

0

2 Answers 2

4

simply,

var result = strings
    .Select(s => s.Split('|'))
    .ToDictionary(a => int.Parse(a[0]), a => int.Parse(a[1]));

if duplicates are allowed,

var result = strings
    .Select(s => s.Split('|'))
    .ToLookup(a => int.Parse(a[0]), a => int.Parse(a[1]));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use ToDictionary method:

var dictionary = stringArray.ToDictionary(x => x.Split('|')[0], x => x.Split('|')[1]);

But you should be aware that this will throw an exception if there are duplicate keys.

2 Comments

of course, it's extremely obvious when the answer is in front of you... thanks
why split it twice, its wastefull

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.