如何在.net中获取数组的唯一值?

时间:2021-06-12 20:31:16

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

说我有这个数组: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"

是否有.net功能可以给我独特的价值?我希望这样的东西作为函数的输出:OutputArray(0)=“aaa”OutputArray(1)=“bbb”

4 个解决方案

#1


8  

Assuming you have .Net 3.5/LINQ:

假设你有.Net 3.5 / LINQ:

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

#2


8  

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

解决方案可能是使用LINQ,如下例所示:

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


2  

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


1  

Use the HashSet class included in .NET 3.5.

使用.NET 3.5中包含的HashSet类。

#1


8  

Assuming you have .Net 3.5/LINQ:

假设你有.Net 3.5 / LINQ:

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

#2


8  

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

解决方案可能是使用LINQ,如下例所示:

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


2  

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


1  

Use the HashSet class included in .NET 3.5.

使用.NET 3.5中包含的HashSet类。