当前位置: 动力学知识库 > 问答 > 编程问答 >

collections - 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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: