How do I remove duplicates from a C# array?

后端 未结 27 2695
北海茫月
北海茫月 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:39

    The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace.

    string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};
    var sList = new ArrayList();
    
    for (int i = 0; i < sArray.Length; i++) {
        if (sList.Contains(sArray[i]) == false) {
            sList.Add(sArray[i]);
        }
    }
    
    var sNew = sList.ToArray();
    
    for (int i = 0; i < sNew.Length; i++) {
        Console.Write(sNew[i]);
    }
    

    You could wrap this up into a function if you wanted to.

提交回复
热议问题