print唯一元素整数数组 [英] print unique elements integer array
本文介绍了print唯一元素整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从数组中打印唯一元素
解决方案
在伪代码中(因为你没有提供有关code \ language语言等的任何信息)
foreach (元素e 在数组中)
{
int count = 0 跨度>;
foreach (元素tmp in 数组)
if (e.equals(tmp)count ++;
if (count < 2 ) // 这意味着它在问题中的要求是唯一的
PrintOrSomethingElse(e); // 执行您在这里使用元素所需的操作或将其收集到一个集合等中
}
干杯,
Edo
使用LINQ将是最简单的。
例如var b = a.Distinct()。ToArray();
。
这里a是你的数组。
它取决于数组元素。
一般来说,你可以使用LINQ to Objects遵循这种方法:
var array = new int [] { 0 , 1 , 2 , 1 , 3 , 1 };
foreach ( int a in array.Distinct())
{
// 用做你想做的事a
}
但如果数组包含对象,则无法正常工作结构。
为此你需要实现一个IEqualityComparer
。有关更为一般的方法,请参阅此文章: Linq Distinct的通用IEqualityComparer( ) [ ^ ]
print unique elements from array
解决方案
In pseudo-code (since you didn''t provide ANY information on the code\language etc)
foreach (element e in array) { int count = 0; foreach (element tmp in array) if (e.equals(tmp) count++; if (count < 2) // that means it is unique as requested in the question PrintOrSomethingElse(e); // perform your desired action with the element here or collect it into a collection etc }
Cheers,
Edo
Using LINQ would be the easiest.
For e.g.var b = a.Distinct().ToArray();
.
Here a is your array.
It depends on the array elements.
In general you can follow this approach using LINQ to Objects:
var array = new int[]{0,1,2,1,3,1}; foreach(int a in array.Distinct()) { //do what you want with a }
But this won''t work if the array contains objects with structure.
For that you need to implement anIEqualityComparer
. See this article for an even more general approach also: A Generic IEqualityComparer for Linq Distinct()[^]
这篇关于print唯一元素整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文