gpt4 book ai didi

c# - 将字符串拆分为字典作为键,列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:00 25 4
gpt4 key购买 nike

我有一个字符串类型,它将以格式返回数千条记录

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 的 1000 条记录,是否有一种比循环更有效/更快速的方法?

更新:测试了各种答案后,以下是“正确”时间

enter image description here

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();
}

最佳答案

以下可能更快,因为字典的构建具有避免重新分配所需的容量:

//short example string - may contain 1000's     
string newstr = ...;

string[] keysAndValues = newstr.Split(':');
var mydictionary = new Dictionary<string, List<string>>(keysAndValues.Length);
foreach (string item in keysAndValues)
{
List<string> list = new List<string>(item.Split(','));
mydictionary.Add(list[0], list);
// remove key from list to match Jon Skeet's implementation
list.RemoveAt(0);
}

虽然可读性不如 Jon Skeet 的 LINQ 版本。

关于c# - 将字符串拆分为字典作为键,列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12474366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com