Remove duplicate elements from an array

    General discussion

  • Hi,
    I want to find and remove the duplicate elements present in my arrays. What would be the most peformance effective solution for that. I can think of using Sorting algorithm, and while sorting if we find any duplicates remove them.

    Any other apporach which is better than this can be appreciated.

    Kiran Kotra
    Monday, August 18, 2008 4:39 AM

All replies

  • Use Contains to keep duplicates out and you'll never have to remove any. 
    Monday, August 18, 2008 6:18 AM
  • i am using plain arrays, not using any collections. i think Contains method is not inherited for simple arrays.
    Monday, August 18, 2008 6:24 AM
  • I assume everyone is using the latest framework.  Sorry.  When you upgrade you'll have Contains for simple arrays.
    Monday, August 18, 2008 6:35 AM
  • I highly recommend upgrading to C# 3 for this problem:
    static void Main(string[] args) { 
        var ints = new[] { 1, 2, 3, 4, 4, 4, 5, 6, 6, 6, 5, 3, 3 }; 
        var no_dupes = ints.Distinct(); //That's it.  Magic. 
        foreach (int i in no_dupes) 
            Console.Write(i + ","); //1,2,3,4,5,6,

    Monday, August 18, 2008 7:20 AM
  • thanks... Distinct() method  is really magic....

    Any other suggestion u can give, if it is C#2.0

    Monday, August 18, 2008 7:30 AM
  • Let's asume you have the sam problem but you are not using linq.Can you show how you ditinct duplicates?
    Wednesday, October 01, 2008 3:12 PM