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

发布于 2024-10-02 06:04:17 字数 170 浏览 0 评论 0原文

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

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

如何获得

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

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

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

how to get

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

琉璃梦幻 2024-10-09 06:04:17

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

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

Easiest way is the LINQ Distinct() command :

var b = a.Distinct().ToArray();
口干舌燥 2024-10-09 06:04:17

您可能需要考虑使用 Set 而不是数组。集合不能包含重复项,因此添加第二个“a”不会产生任何效果。这样,您的字符集合将始终不包含重复项,并且您无需对其进行任何后期处理。

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.

王权女流氓 2024-10-09 06:04:17
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");

var countItems = list.Count(); //in this case countItems=1
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");

var countItems = list.Count(); //in this case countItems=1
余罪 2024-10-09 06:04:17

开始时的数组是 IEnumerableIEnumerable 有一个 Distinct() 方法,可用于将列表操作为不同的值

var distinctList = list.Distinct();

最后,IEnumerable 有一个 ToArray() 方法:

var b = distinctList.ToArray();

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

var distinctList = list.Distinct();

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

var b = distinctList.ToArray();
真心难拥有 2024-10-09 06:04:17

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文