我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
当前回答
public static int RemoveDuplicates(ref int[] array)
{
int size = array.Length;
// if 0 or 1, return 0 or 1:
if (size < 2) {
return size;
}
int current = 0;
for (int candidate = 1; candidate < size; ++candidate) {
if (array[current] != array[candidate]) {
array[++current] = array[candidate];
}
}
// index to count conversion:
return ++current;
}
其他回答
你可以使用一个LINQ查询来做到这一点:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
将所有字符串添加到字典中,然后获取Keys属性。这将产生每个唯一的字符串,但不一定与原始输入的顺序相同。
如果你要求最终结果与原始输入的顺序相同,当你考虑每个字符串的第一次出现时,使用以下算法:
有一个列表(最终输出)和一个字典(检查重复) 对于输入中的每个字符串,检查它是否已经存在于字典中 如果不是,将它同时添加到字典和列表中
最后,列表包含每个唯一字符串的第一次出现。
在编写词典时,一定要考虑到文化等因素,以确保正确处理带有重音字母的重复项。
public static int RemoveDuplicates(ref int[] array)
{
int size = array.Length;
// if 0 or 1, return 0 or 1:
if (size < 2) {
return size;
}
int current = 0;
for (int candidate = 1; candidate < size; ++candidate) {
if (array[current] != array[candidate]) {
array[++current] = array[candidate];
}
}
// index to count conversion:
return ++current;
}
List<String> myStringList = new List<String> (); foreach (myStringArray中的字符串) { 如果(! myStringList.Contains (s)) { myStringList.Add(年代); } }
这是O(n²),这对于一个短列表来说没有什么关系因为它将被塞进一个组合中,但对于一个大的集合来说可能很快就会成为一个问题。
如果您需要对它进行排序,那么您可以实现一个也删除重复项的排序。
那就一石二鸟了。