How to remove duplicates from a StringCollection in c#? I was looking for a more efficient approach. 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();
using linq: myCollection.Cast<string>.Distinct().ToList();
or you can use a HashSet as Noldorin proposed
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()