0

I have data like:

Dictionary<string, string> dic = new Dictionary<string, string>();    
dic.Add("1", "ABC1");    
dic.Add("2", "ABC2");    
dic.Add("3", "ABC3");    
dic.Add("4", "ABC4");    
dic.Add("5", "ABC5");    
dic.Add("6", "ABC6");  
string[] col = new string[] { "1", "4", "5" };

needed a result string array in the same order as col array like:

string[] res = new string[] { "ABC1", "ABC4", "ABC5" }; 

tried with for loop but needed in linq

string[] res = new string[col.Length]; // { "ABC1", "ABC4", "ABC5" };

for(int i=0;i<col.Length;i++)
{
    res[i] = dic[col[i]];
}
2
  • 7
    Hint: LINQ's Select and ToArray methods make this very simple. Commented Oct 14, 2016 at 10:14
  • 1
    I see a LINQ tag but no evidence that you tried to solve this with LINQ? Commented Oct 14, 2016 at 10:15

2 Answers 2

9

The unsafe way is just to Select directly from dictionary:

var result = col.Select(c => dic[c]).ToArray();

But it is more recommended to check that the key is in the dictionary to avoid exception

var result = col.Where(c => dic.Keys.Contains(c))
                .Select(c => dic[c])
                .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var result = dic.Where(k => col.Contains(k.Key)).Select(v => v.Value).ToArray();

2 Comments

string[] col = new string[] { "1", "5", "4" }; if col array is like this then result is still lke { "ABC1", "ABC4", "ABC5" }; but i want { "ABC1", "ABC5", "ABC4" };
Right. Then @GiladGreen's answer should do it.

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.