Tasawer Khan
Tasawer Khan

Reputation: 6148

How to remove duplicates from a StringCollection in c#?

How to remove duplicates from a StringCollection in c#? I was looking for a more efficient approach. StringCollection is returned from an API.

Upvotes: 1

Views: 3199

Answers (4)

Rowland Shaw
Rowland Shaw

Reputation: 38130

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()

Upvotes: 1

pierroz
pierroz

Reputation: 7870

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

Upvotes: 0

Noldorin
Noldorin

Reputation: 147340

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

Upvotes: 10

Ta01
Ta01

Reputation: 31610

    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.

Upvotes: 1

Related Questions