开发者

How to remove duplicates from a StringCollection in c#?

开发者 https://www.devze.com 2022-12-27 13:24 出处:网络
How to remove duplicates from a StringCollection in c#? I was looking for a more efficient a开发者_Go百科pproach. StringCollection is returned from an API.Just use a HashSet<string> as your coll

How to remove duplicates from a StringCollection in c#? I was looking for a more efficient a开发者_Go百科pproach. StringCollection is returned from an API.


Just use a HashSet<string> as your collection, rather than StringCollection. It is designed to prevent the addition of duplicate elements by comparing hash codes of those elements (thus being very efficient).

Edit: Since it would seem you're returned a StringCollection in the first place, then the solution should just be to loop over all the items in the StringCollection and add them to a HashSet<string>, thereby eliminating duplicates. The Enumerable.Distinct extension method would also do the job, but less efficiently I suspect, since it does use hashing (rather just normal equality testing). Something like this:

var noDuplicatesItems = stringCollection.Cast<string>().Distinct().ToArray();


    StringCollection s = new StringCollection();
    s.Add("s");
    s.Add("s");
    s.Add("t");

    var uniques = s.Cast<IEnumerable>();
    var unique = uniques.Distinct();

    foreach (var x in unique)
    {
        Console.WriteLine(x);
    }

    Console.WriteLine("Done");
    Console.Read();

Not tested for efficiency.


If you're in v3.5 of the Framework (or later), then you can first convert to an IEnumerable<string>, and then call the Distinct() method on that; ie:

// where foo is your .Collections.Specialized.StringCollection
IEnumerable<string> distinctList = foo.OfType<string>.Distinct()


using linq: myCollection.Cast<string>.Distinct().ToList(); or you can use a HashSet as Noldorin proposed

0

精彩评论

暂无评论...
验证码 换一张
取 消