Which method of adding items to the ASP.NET Dictionary class is more efficient?
- by ahmd0
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);
}
}