views:

811

answers:

4

Say I've got this array: MyArray(0)="aaa" MyArray(1)="bbb" MyArray(2)="aaa"

Is there a .net function which can give me the unique values? I would like something like this as an output of the function: OutputArray(0)="aaa" OutputArray(1)="bbb"

+1  A: 

You could use a dictionary to add them with a key, and when you add them check if the key already exists.

string[] myarray = new string[] { "aaa", "bbb", "aaa" };
            Dictionary mydict = new Dictionary();
            foreach (string s in myarray) {
                if (!mydict.ContainsKey(s)) mydict.Add(s, s);
            }
Stormenet
+1  A: 

Use the HashSet class included in .NET 3.5.

leppie
+8  A: 

A solution could be to use LINQ as in the following example:

int[] test = { 1, 2, 1, 3, 3, 4, 5 };
var res = (from t in test select t).Distinct<int>();
foreach (var i in res)
{
    Console.WriteLine(i);
}

That would print the expected:

1
2
3
4
5
smink
+4  A: 

Assuming you have .Net 3.5/LINQ:

string[] OutputArray = MyArray.Distinct().ToArray();
James Curran