How can I get the unique values of an array in .net?

我们两清 提交于 2020-01-03 13:31:55

问题


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:


Assuming you have .Net 3.5/LINQ:

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



回答2:


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



回答3:


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



回答4:


Use the HashSet class included in .NET 3.5.



来源:https://stackoverflow.com/questions/83260/how-can-i-get-the-unique-values-of-an-array-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!