How to remove duplicates from a StringCollection in c#? I was looking for a more efficient approach. StringCollection is returned from an API.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Just use a
HashSet<string>as your collection, rather thanStringCollection. 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
StringCollectionin the first place, then the solution should just be to loop over all the items in theStringCollectionand add them to aHashSet<string>, thereby eliminating duplicates. TheEnumerable.Distinctextension method would also do the job, but less efficiently I suspect, since it does use hashing (rather just normal equality testing). Something like this: