我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
当前回答
你可以使用一个LINQ查询来做到这一点:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
其他回答
protected void Page_Load(object sender, EventArgs e)
{
string a = "a;b;c;d;e;v";
string[] b = a.Split(';');
string[] c = b.Distinct().ToArray();
if (b.Length != c.Length)
{
for (int i = 0; i < b.Length; i++)
{
try
{
if (b[i].ToString() != c[i].ToString())
{
Response.Write("Found duplicate " + b[i].ToString());
return;
}
}
catch (Exception ex)
{
Response.Write("Found duplicate " + b[i].ToString());
return;
}
}
}
else
{
Response.Write("No duplicate ");
}
}
将所有字符串添加到字典中,然后获取Keys属性。这将产生每个唯一的字符串,但不一定与原始输入的顺序相同。
如果你要求最终结果与原始输入的顺序相同,当你考虑每个字符串的第一次出现时,使用以下算法:
有一个列表(最终输出)和一个字典(检查重复) 对于输入中的每个字符串,检查它是否已经存在于字典中 如果不是,将它同时添加到字典和列表中
最后,列表包含每个唯一字符串的第一次出现。
在编写词典时,一定要考虑到文化等因素,以确保正确处理带有重音字母的重复项。
下面是一个简单的java逻辑,你遍历数组的元素两次,如果你看到任何相同的元素,你赋0给它,加上你不触及你正在比较的元素的索引。
import java.util.*;
class removeDuplicate{
int [] y ;
public removeDuplicate(int[] array){
y=array;
for(int b=0;b<y.length;b++){
int temp = y[b];
for(int v=0;v<y.length;v++){
if( b!=v && temp==y[v]){
y[v]=0;
}
}
}
}
简单的解决方案:
using System.Linq;
...
public static int[] Distinct(int[] handles)
{
return handles.ToList().Distinct().ToArray();
}
——这是面试中每次都会问的问题。现在我完成了它的编码。
static void Main(string[] args)
{
int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 };
int numDups = 0, prevIndex = 0;
for (int i = 0; i < array.Length; i++)
{
bool foundDup = false;
for (int j = 0; j < i; j++)
{
if (array[i] == array[j])
{
foundDup = true;
numDups++; // Increment means Count for Duplicate found in array.
break;
}
}
if (foundDup == false)
{
array[prevIndex] = array[i];
prevIndex++;
}
}
// Just Duplicate records replce by zero.
for (int k = 1; k <= numDups; k++)
{
array[array.Length - k] = '\0';
}
Console.WriteLine("Console program for Remove duplicates from array.");
Console.Read();
}