Which method of adding items to the ASP.NET Dictionary class is more efficient?

Posted by ahmd0 on Stack Overflow See other posts from Stack Overflow or by ahmd0
Published on 2012-04-08T23:11:37Z Indexed on 2012/04/08 23:30 UTC
Read the original article Hit count: 188

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET