【发布时间】:2012-09-18 09:42:45
【问题描述】:
我有一个字符串类型,它将以这种格式返回数千条记录
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();
}
【问题讨论】:
-
您的值实际上是否以字符串形式出现?或者是否有任何值的“流式传输”?
-
循环是必须要发生的,而且经常自己写是最快的。
-
从外观上看,您当前的代码包含项目列表中的键 - 这是正确的/有问题吗?
-
它们以字符串形式出现,格式显示为一个大字符串。是的,字符串还包括唯一键。
-
您当前的实现是否存在性能瓶颈?除非您对数据进行预处理,否则无论使用 RegEx 或 LINQ 还是常规字符串操作,您总是必须像以前那样拆分字符串。