How do I remove duplicates from a C# array?

lomaxx picture lomaxx · Aug 13, 2008 · Viewed 328.9k times · Source

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 wondering if there was a better way to do it, possibly by using a temp array.

What is the best way to remove duplicates from a C# array?

Answer

Jeff Atwood picture Jeff Atwood · Aug 13, 2008

You could possibly use a LINQ query to do this:

int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();