我在csv文件中有关于课程,学生ID和学生姓名的一些数据,如下所示:
4,3,约翰(上课,学生姓名,学生姓名)
3,3,简
4,4,哈利2,3,哈利
3,5,珍妮
2,1,乔
我需要将上述数据读入SortedDictionary>结构,外部字典将类存储为键,内部字典存储学生ID和学生名称。
我的代码有点像以下:
string line = string.Empty;
string[] data = null;
SortedDictionary<int, string> studentDictionary = new SortedDictionary<int, string>();
SortedDictionary<int, SortedDictionary<int, string>> classDictionary = new SortedDictionary<int, SortedDictionary<int, string>>();
using (StreamReader sr = new StreamReader(schoolCSV))
{
while (!sr.EndOfStream)
{
line = sr.ReadLine();
data = line.Split(new char[] { ',' }, StringSplitOptions.None);
studentDictionary.Add(Convert.ToInt32(data[1].Trim()), data[2]);
// I get error in the above line, when it parses the second row
}
}
我无法将其正确检索到排序词典的排序字典中。有人能告诉我正确的方法吗?
答案 0 :(得分:0)
一点点LINQ可能会有所帮助。
首先,您需要一种将IEnumerable<T>
转换为SortedDictionary<TKey, TValue>
的扩展方法:
using System;
using System.Collections.Generic;
namespace YourNamespace
{
public static class SortedDictionaryExtensions
{
public static SortedDictionary<TKey, TValue> ToSortedDictionary<TSource, TKey, TValue>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TValue> valueSelector)
{
var result = new SortedDictionary<TKey, TValue>();
foreach (TSource item in source)
{
TKey key = keySelector(item);
TValue value = valueSelector(item);
result.Add(key, value);
}
return result;
}
}
}
然后,您可以将GroupBy
与新的扩展方法结合使用,以生成结果:
SortedDictionary<int, SortedDictionary<int, string>> classDictionary;
classDictionary = File.ReadLines(schoolCSV)
.Select(line => line.Split(','))
.Select(data => new
{
ClassId = int.Parse(data[0]),
StudentId = int.Parse(data[1]),
StudentName = data[2]
})
.GroupBy(item => item.ClassId, (key, items) => new
{
ClassId = key,
Students = items.ToSortedDictionary(i => i.StudentId, i => i.StudentName)
})
.ToSortedDictionary(item => item.ClassId, item => item.Students);