gpt4 book ai didi

c# - 哪种向 ASP.NET Dictionary 类添加项目的方法效率更高?

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

我在 ASP.NET 中使用 C# 将逗号分隔的字符串列表转换为字典(通过省略任何重复项):

string str = "1,2, 4, 2, 4, item 3,item2, item 3"; //Just a random string for the sake of this example

我想知道哪种方法更有效?

1 - 使用 try/catch block :

Dictionary<string, string> dic = new Dictionary<string, string>();

string[] strs = str.Split(',');
foreach (string s in strs)
{
if (!string.IsNullOrWhiteSpace(s))
{
try
{
string s2 = s.Trim();
dic.Add(s2, s2);
}
catch
{
}
}
}

2 - 或者使用 ContainsKey() 方法:

string[] strs = str.Split(',');
foreach (string s in strs)
{
if (!string.IsNullOrWhiteSpace(s))
{
string s2 = s.Trim();
if (!dic.ContainsKey(s2))
dic.Add(s2, s2);
}
}

编辑。感谢所有参与的人!

一个非常有趣的发现。如果你看下面dtb提供的答案,他提出了两种使用hashSet的方法。我将在这里配音:

方法一:

var hashSet = new HashSet<string>(from s in str.Split(',')
where !string.IsNullOrWhiteSpace(s)
select s.Trim());

方法二:

var hashSet = new HashSet<string>();
foreach (string s in str.Split(','))
{
if (!string.IsNullOrWhiteSpace(s))
{
hashSet.Add(s.Trim());
}
}

我问他哪种方法性能更快,有趣的是,方法 2 更快。下面是使用 Stopwatch 类完成的计时,方法是循环运行 Release 构建中的每个方法 1,000,000 次:

Method 1: 1,440 ms average
Method 2: 1,124 ms average

最佳答案

如果您需要一套而不是字典,我建议您使用 HashSet<T> Class :

HashSet<T> Class

Represents a set of values.

A set is a collection that contains no duplicate elements, and whose elements are in no particular order.


var hashSet = new HashSet<string>(from s in str.Split(',')
where !string.IsNullOrWhiteSpace(s)
select s.Trim());

或同样

var hashSet = new HashSet<string>();
foreach (string s in str.Split(','))
{
if (!string.IsNullOrWhiteSpace(s))
{
hashSet.Add(s.Trim());
}
}

关于c# - 哪种向 ASP.NET Dictionary 类添加项目的方法效率更高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10067315/

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