0

I have varying string values that I want to add to a key inside a dictionary.

What is the correct answer(key)
AnswerA(value)
AnswerB(value)
AnswerC(value)

I am doing this by using the split on a string(which happens in a loop).

string[] arr = l.ContentDescription.Split('|').ToArray();
Dictionary<string, List<string>> questions = new Dictionary<string, List<string>>();

for (int i = 0; i < arr.Length - 1; i++)
{
    var arrB = arr[i + 1].Split('*').ToArray();
    //all theanswers should now be added to the list 
    questions.Add(arrB[0], new List<string>() { });
}

arr looks something like this

Choose the correct answer and submit|What is the correct answer*AnswerA*AnswerB*AnswerC

What is the best way of adding these answer values if they vary in length

1
  • 1
    Maybe questions.Add(arrB[0], arrB.Skip(1).ToList() ); ? Commented Apr 28, 2016 at 9:20

2 Answers 2

2

Just skip the first element in your array (Linq):

questions.Add(arrB[0], arrB.Skip(1).ToList());
Sign up to request clarification or add additional context in comments.

Comments

1

As I mentioned in the comment, a quick solution is to use Skip like this:

questions.Add(arrB[0], arrB.Skip(1).ToList());

Here is how I would do it all in LINQ:

var questions =
    l.ContentDescription
    .Split('|')
    .Skip(1) //get rid of "Choose the correct answer and submit"
    .Select(x => x.Split('*'))
    .ToDictionary(x => x[0], x => x.Skip(1).ToList());

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.