我有一个字符串类型,它将以格式返回数千条记录
key1,val1,val2,val3,val4,val5:key2,val6,val7,val8,val9,val10:key3,val11,val12,val13,val14,val15
我想将它作为 Key,List 分配给字典,所以它看起来像
key1,[val1,val2,val3,val4,val5]
key2,[val6,val7,val8,val9,val10]
key3,[val11,val12,val13,val14,val15]
. . .
字符串中的所有键都是唯一的,并且所有记录的列表大小都是恒定的。
目前我正在使用拆分并使用循环每个记录
//short example string - may contain 1000's
string newstr = @"key1,val1,val2,val3,val4,val5:key2,val6,val7,val8,val9,val10:key3,val11,val12,val13,val14,val15";
Dictionary<string, List<string>> mydictionary = new Dictionary<string, List<string>>();
foreach (string item in newstr.Split(':'))
{
List<string> list = new List<string>(item.Split(','));
mydictionary.Add(list[0], list);
}
我的问题是,有没有更有效/更快的方法来使用 C#4.0 而不是循环来处理 1000 条记录?
更新:测试了各种答案后,以下是“正确”时间
static void Main(string[] args)
{
System.IO.StreamReader myFile = new System.IO.StreamReader(@"C:\Users\ooo\Desktop\temp.txt");
string newstr = myFile.ReadToEnd();
myFile.Close();
TimeSpan ts;
TimeSpan te;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
ts = stopWatch.Elapsed;
Dictionary<string, List<string>> mydictionary = new Dictionary<string, List<string>>();
foreach (string item in newstr.Split(':'))
{
List<string> list = new List<string>(item.Split(','));
mydictionary.Add(list[0], list);
}
te = stopWatch.Elapsed;
Console.WriteLine("MyTime: " + (te - ts).ToString());
ts = stopWatch.Elapsed;
var result = newstr.Split(':')
.Select(line => line.Split(','))
.ToDictionary(bits => bits[0],
bits => bits.Skip(1).ToList());
te = stopWatch.Elapsed;
Console.WriteLine("JonSkeet: " + (te - ts).ToString());
ts = stopWatch.Elapsed;
string[] keysAndValues = newstr.Split(':');
var newdictionary = new Dictionary<string, List<string>>(keysAndValues.Length);
foreach (string item in keysAndValues)
{
List<string> list = new List<string>(item.Split(','));
newdictionary.Add(list[0], list);
}
te = stopWatch.Elapsed;
Console.WriteLine("Joe: " + (te - ts).ToString());
Console.WriteLine("Records: " + mydictionary.Count.ToString());
stopWatch.Stop();
}