How do I remove duplicates from a C# array?

后端 未结 27 2692
北海茫月
北海茫月 2020-11-22 07:53

I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was w

27条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 08:48

    Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.

    If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:

    1. Have a list (final output) and a dictionary (to check for duplicates)
    2. For each string in the input, check if it exists in the dictionary already
    3. If not, add it both to the dictionary and to the list

    At the end, the list contains the first occurance of each unique string.

    Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.

提交回复
热议问题