2

I know that Linq offers the ToDictionary(key, value) method, and I'm sure there's a way to be able to do what I'm trying to achieve but I can't quite figure it out.

I have two arrays, the first being conditionalIds, which is simply an int[] that stores a number of Ids, the second array is a string[] called conditionalAnswers. I essentially want to combine and map these two arrays so that each of the Ids stores in conditionalIds maps to the correct answer.

var conditionalIds = _currentRuleSet.MultiConditionalQuestionIds;
var conditionalAnswers = _currentRuleSet.MultiConditionalQuestionAnswers;
var map = conditionalAnswers.ToDictionary(conditionalIds, x => x[]);

However I'm not sure how to structure the Linq query to achieve this.

2
  • 1
    why linq? do both lists have the same number of values? Commented May 20, 2019 at 8:45
  • 1
    How do you know what is the correct answer of a given id? Commented May 20, 2019 at 8:53

4 Answers 4

3

Assuming both lists have the same number of items and they are in the correct order, you want to use Linq Enumerable.Zip, for example this will give you an IEnumerable of an anonymous type:

var map = conditionalIds.Zip(
    conditionalAnswers, 
    (id, answer) => new { id, answer });

And if you really want a dictionary:

var dictionary = map.ToDictionary(x => x.id, x => x.answer);
Sign up to request clarification or add additional context in comments.

Comments

1

Ans given by @SeM is correct, but one thing is that question id array should have unique values.

    int[] queId={6,4,9,2,10};
string[] answers ={"Ans1", "Ans3","Ans4","Ans16","Ans18"} ;
Dictionary<int, string> queAnsBank=answers.select((value,index)=>new{Key=queId[index],Value=value}).ToDictionary(i=>i.Key,i=>i.Value);

You can also achieve this by for loop.

Comments

0

It looks like target dictionary could be constructed as:

        Dictionary<int, string> map = conditionalIds.ToDictionary(
            keySelector: id => id,
            elementSelector: id => conditionalAnswers[id]);

Comments

0

If you are trying to map based on conditionalAnswers and conditionalIds indices, you can do something like this:

var map = conditionalAnswers
          .Select((s, i) => new { Key = conditionalIds[i], Value = s })
          .ToDictionary(d => d.Key, d => d.Value);

References: Enumerable.Select Method

Comments

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.