将不同的字符串值添加到字典中的List

时间:2016-04-28 09:13:22

标签: c# dictionary

我有不同的字符串值,我想添加到字典中的键。

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

我是通过在字符串上使用split(在循环中发生)来完成此操作。

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看起来像这样

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

如果长度不同,添加这些答案值的最佳方法是什么

2 个答案:

答案 0 :(得分:2)

跳过数组中的第一个元素(Linq):

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

答案 1 :(得分:1)

正如我在评论中提到的,快速解决方案是使用Skip,如下所示:

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

以下是我将如何在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());
相关问题