何千ものレコードをフォーマットで返す文字列型があります
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]
。。。
すべてのキーは文字列内で一意であり、リストサイズはすべてのレコードで一定です。
現在、Splitを使用しており、各レコードをループしています。
//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を使用して数千のレコードに対してこれを行うためのより効率的で迅速な方法はありますか?
更新:さまざまな答えをテストした後、以下は「正しい」時間です
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();
}