c#数组,如何使数组中的数据彼此不同?

时间:2021-07-31 07:58:35

C# Array, How to make data in an array distinct from each other? For example

c#数组,如何使数组中的数据彼此不同?例如

string[] a = {"a","b","a","c","b","b","c","a"}; 

how to get

如何让

string[]b = {"a","b","c"}

5 个解决方案

#1


20  

Easiest way is the LINQ Distinct() command :

最简单的方法是LINQ Distinct()命令:

var b = a.Distinct().ToArray();

#2


6  

You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.

您可能需要考虑使用集合而不是数组。集合不能包含重复,所以添加第二个“a”将没有任何效果。这样,你的字符集合将永远不会包含重复的字符,并且你不必对其进行任何post处理。

#3


2  

    var list = new HashSet<string> { };
    list.Add("a");
    list.Add("a");

    var countItems = list.Count(); //in this case countItems=1

#4


1  

An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values

开始时,数组是IEnumerable 。IEnumerable 有一个独特的()方法,可以用来将列表操作到其不同的值中。

var distinctList = list.Distinct();

Finally,IEnumerable<T> has a ToArray() method:

最后,IEnumerable 有ToArray()方法:

var b = distinctList.ToArray();

#5


0  

I think using c# Dictionary is the better way and I can sort by value using LINQ

我认为使用c#字典是更好的方法,我可以使用LINQ按值排序

#1


20  

Easiest way is the LINQ Distinct() command :

最简单的方法是LINQ Distinct()命令:

var b = a.Distinct().ToArray();

#2


6  

You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.

您可能需要考虑使用集合而不是数组。集合不能包含重复,所以添加第二个“a”将没有任何效果。这样,你的字符集合将永远不会包含重复的字符,并且你不必对其进行任何post处理。

#3


2  

    var list = new HashSet<string> { };
    list.Add("a");
    list.Add("a");

    var countItems = list.Count(); //in this case countItems=1

#4


1  

An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values

开始时,数组是IEnumerable 。IEnumerable 有一个独特的()方法,可以用来将列表操作到其不同的值中。

var distinctList = list.Distinct();

Finally,IEnumerable<T> has a ToArray() method:

最后,IEnumerable 有ToArray()方法:

var b = distinctList.ToArray();

#5


0  

I think using c# Dictionary is the better way and I can sort by value using LINQ

我认为使用c#字典是更好的方法,我可以使用LINQ按值排序