Domanda

Diciamo che ho questo array:MyArray (0) = "AAA" MyArray (1) = "BBB" MyArray (2) = "AAA"

Esiste una funzione .net che può darmi valori univoci?Vorrei qualcosa di simile come output della funzione:OutputArray (0) = "AAA" outputArray (1) = "BBB"

È stato utile?

Soluzione

Supponendo che tu abbia .Net 3.5/LINQ:

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

Altri suggerimenti

Una soluzione potrebbe essere quella di utilizzare LINQ come nell'esempio seguente:

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);
}

Ciò stamperebbe il previsto:

1
2
3
4
5

Potresti usare un dizionario per aggiungerli con una chiave e quando li aggiungi controlla se la chiave esiste già.

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

Usare la classe HashSet inclusa in .NET 3,5.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top