I’m converting a comma separated list of strings into a dictionary using C# in ASP.NET (by omitting any duplicates):
string str = "1,2, 4, 2, 4, item 3,item2, item 3"; //Just a random string for the sake of this example
and I was wondering which method is more efficient?
1 – Using 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 – Or using ContainsKey() method:
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);
}
}
EDIT. Thank you everyone who participated!
A very interesting find. If you look at the answer provided by dtb below, he proposed two methods of using hashSet. I’ll dub them over here:
Method 1:
var hashSet = new HashSet<string>(from s in str.Split(',')
where !string.IsNullOrWhiteSpace(s)
select s.Trim());
Method 2:
var hashSet = new HashSet<string>();
foreach (string s in str.Split(','))
{
if (!string.IsNullOrWhiteSpace(s))
{
hashSet.Add(s.Trim());
}
}
I asked him which method is faster performance-wise, and interestingly enough, method 2 is faster. Here’s the timing done using the Stopwatch class by running each method in a Release build for 1,000,000 times in a loop:
Method 1: 1,440 ms average
Method 2: 1,124 ms average
If you need a set and not a dictionary, I recommend you use the HashSet<T> Class:
or equally