I have been working with a string[]
array in C# that gets returned from a function call. I could possibly cast to a Generic
collection, but I was wondering if there was a better way to do it, possibly by using a temp array.
我一直在使用c#中的字符串[]数组,该数组从函数调用中返回。我可以对一个通用集合进行强制转换,但是我想知道是否有更好的方法,可能是使用一个临时数组。
What is the best way to remove duplicates from a C# array?
从c#数组中删除重复内容的最佳方式是什么?
20 个解决方案
#1
355
You could possibly use a LINQ query to do this:
您可以使用LINQ查询完成以下操作:
int[] s = { 1, 2, 3, 3, 4};int[] q = s.Distinct().ToArray();
#2
50
Here is the HashSet<string> approach:
这里是HashSet
public static string[] RemoveDuplicates(string[] s){ HashSet<string> set = new HashSet<string>(s); string[] result = new string[set.Count]; set.CopyTo(result); return result;}
Unfortunately this solution also requires .NET framework 3.5 or later as HashSet was not added until that version. You could also use array.Distinct(), which is a feature of LINQ.
不幸的是,这个解决方案还需要。net framework 3.5或更高版本,因为HashSet是在那个版本之前没有添加的。您还可以使用array.Distinct(),这是LINQ的一个特性。
#3
11
If you needed to sort it, then you could implement a sort that also removes duplicates.
如果您需要对它进行排序,那么您可以实现同样可以删除重复的排序。
Kills two birds with one stone, then.
一举两得。
#4
8
This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:
这可能取决于您希望设计解决方案的程度——如果数组永远不会那么大,而且您不关心排序列表,那么您可能希望尝试以下类似的方法:
public string[] RemoveDuplicates(string[] myList) { System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in myList) if (!newList.Contains(str)) newList.Add(str); return (string[])newList.ToArray(typeof(string)); }
#5
7
The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace.
下面的测试和工作代码将从数组中删除副本。您必须包括系统。集合名称空间。
string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};var sList = new ArrayList();for (int i = 0; i < sArray.Length; i++) { if (sList.Contains(sArray[i]) == false) { sList.Add(sArray[i]); }}var sNew = sList.ToArray();for (int i = 0; i < sNew.Length; i++) { Console.Write(sNew[i]);}
You could wrap this up into a function if you wanted to.
如果你愿意,你可以把它打包成一个函数。
#6
6
-- This is Interview Question asked every time. Now i done its coding.
这是每次面试的问题。现在我完成了它的编码。
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(); }
#7
5
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 "); }}
#8
5
List<String> myStringList = new List<string>();foreach (string s in myStringArray){ if (!myStringList.Contains(s)) { myStringList.Add(s); }}
This is O(n^2), which won't matter for a short list which is going to be stuffed into a combo, but could be rapidly be a problem on a big collection.
这是O(n ^ 2),不重要的名单将被塞进一个组合,但可以迅速成为一个问题在大集合。
#9
4
Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.
将所有字符串添加到字典中,然后获取Keys属性。这将产生每个唯一的字符串,但不一定是以原始输入的顺序。
If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:
如果您要求最终结果与原始输入的顺序相同,当您考虑每个字符串的第一次出现时,请使用以下算法:
- Have a list (final output) and a dictionary (to check for duplicates)
- 有一个列表(最终输出)和一个字典(检查副本)
- For each string in the input, check if it exists in the dictionary already
- 对于输入中的每个字符串,检查它是否已经存在于字典中
- If not, add it both to the dictionary and to the list
- 如果不是,将它添加到字典和列表中。
At the end, the list contains the first occurance of each unique string.
最后,列表包含每个唯一字符串的第一次出现。
Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.
在构建字典时,一定要考虑文化等因素,以确保正确地处理重音字母的重复。
#10
4
The following piece of code attempts to remove duplicates from an ArrayList though this is not an optimal solution. I was asked this question during an interview to remove duplicates through recursion, and without using a second/temp arraylist:
下面的代码试图从ArrayList中删除重复的内容,但这不是最佳的解决方案。在一次采访中,我被问到这个问题:通过递归删除重复内容,而不使用第二个/临时arraylist:
private void RemoveDuplicate() {ArrayList dataArray = new ArrayList(5); dataArray.Add("1"); dataArray.Add("1"); dataArray.Add("6"); dataArray.Add("6"); dataArray.Add("6"); dataArray.Add("3"); dataArray.Add("6"); dataArray.Add("4"); dataArray.Add("5"); dataArray.Add("4"); dataArray.Add("1"); dataArray.Sort(); GetDistinctArrayList(dataArray, 0);}private void GetDistinctArrayList(ArrayList arr, int idx){ int count = 0; if (idx >= arr.Count) return; string val = arr[idx].ToString(); foreach (String s in arr) { if (s.Equals(arr[idx])) { count++; } } if (count > 1) { arr.Remove(val); GetDistinctArrayList(arr, idx); } else { idx += 1; GetDistinctArrayList(arr, idx); } }
#11
4
Maybe hashset which do not store duplicate elements and silently ignore requests to addduplicates.
可能是hashset不存储重复的元素,并且静默地忽略添加重复的请求。
static void Main(){ string textWithDuplicates = "aaabbcccggg"; Console.WriteLine(textWithDuplicates.Count()); var letters = new HashSet<char>(textWithDuplicates); Console.WriteLine(letters.Count()); foreach (char c in letters) Console.Write(c); Console.WriteLine(""); int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 }; Console.WriteLine(array.Count()); var distinctArray = new HashSet<int>(array); Console.WriteLine(distinctArray.Count()); foreach (int i in distinctArray) Console.Write(i + ",");}
#12
4
Here is a O(n*n) approach that uses O(1) space.
这里有一个O(n*n)方法,它使用O(1)空间。
void removeDuplicates(char* strIn){ int numDups = 0, prevIndex = 0; if(NULL != strIn && *strIn != '\0') { int len = strlen(strIn); for(int i = 0; i < len; i++) { bool foundDup = false; for(int j = 0; j < i; j++) { if(strIn[j] == strIn[i]) { foundDup = true; numDups++; break; } } if(foundDup == false) { strIn[prevIndex] = strIn[i]; prevIndex++; } } strIn[len-numDups] = '\0'; }}
The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ.
上面的散列/linq方法是您在现实生活中通常使用的方法。然而,在面试中,他们通常想要施加一些约束,比如常量空间排除散列或没有内部api——这就排除了使用LINQ的可能性。
#13
3
NOTE : NOT tested!
注意:不是测试!
string[] test(string[] myStringArray){ List<String> myStringList = new List<string>(); foreach (string s in myStringArray) { if (!myStringList.Contains(s)) { myStringList.Add(s); } } return myStringList.ToString();}
Might do what you need...
可能做你需要的……
EDIT Argh!!! beaten to it by rob by under a minute!
编辑啊! ! !一分钟之内被罗伯打败了!
#14
3
Tested the below & it works. What's cool is that it does a culture sensitive search too
测试下面的和它的工作。酷的是它也做文化敏感的搜索
class RemoveDuplicatesInString{ public static String RemoveDups(String origString) { String outString = null; int readIndex = 0; CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo; if(String.IsNullOrEmpty(origString)) { return outString; } foreach (var ch in origString) { if (readIndex == 0) { outString = String.Concat(ch); readIndex++; continue; } if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1) { //Unique char as this char wasn't found earlier. outString = String.Concat(outString, ch); } readIndex++; } return outString; } static void Main(string[] args) { String inputString = "aAbcefc"; String outputString; outputString = RemoveDups(inputString); Console.WriteLine(outputString); }
}
}
--AptSenSDET
——AptSenSDET
#15
3
This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :)
这段代码100%地从一个数组中删除重复的值,就像我使用的一样。你可以把它转换成任何OO语言……:)
for(int i=0;i<size;i++){ for(int j=i+1;j<size;j++) { if(a[i] == a[j]) { for(int k=j;k<size;k++) { a[k]=a[k+1]; } j--; size--; } }}
#16
3
Simple solution:
简单的解决方案:
using System.Linq;...public static int[] Distinct(int[] handles){ return handles.ToList().Distinct().ToArray();}
#17
1
you can using This code when work with an ArrayList
当使用ArrayList时,可以使用此代码
ArrayList arrayList;//Add some Members :)arrayList.Add("ali");arrayList.Add("hadi");arrayList.Add("ali");//Remove duplicates from array for (int i = 0; i < arrayList.Count; i++) { for (int j = i + 1; j < arrayList.Count ; j++) if (arrayList[i].ToString() == arrayList[j].ToString()) arrayList.Remove(arrayList[j]);
#18
1
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;}
#19
0
Below is an simple logic in java you traverse elements of array twice and if you see any same element you assign zero to it plus you don't touch the index of element you are comparing.
下面是一个简单的逻辑,在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; } } }}
#20
0
private static string[] distinct(string[] inputArray) { bool alreadyExists; string[] outputArray = new string[] {}; for (int i = 0; i < inputArray.Length; i++) { alreadyExists = false; for (int j = 0; j < outputArray.Length; j++) { if (inputArray[i] == outputArray[j]) alreadyExists = true; } if (alreadyExists==false) { Array.Resize<string>(ref outputArray, outputArray.Length + 1); outputArray[outputArray.Length-1] = inputArray[i]; } } return outputArray; }
#1
355
You could possibly use a LINQ query to do this:
您可以使用LINQ查询完成以下操作:
int[] s = { 1, 2, 3, 3, 4};int[] q = s.Distinct().ToArray();
#2
50
Here is the HashSet<string> approach:
这里是HashSet
public static string[] RemoveDuplicates(string[] s){ HashSet<string> set = new HashSet<string>(s); string[] result = new string[set.Count]; set.CopyTo(result); return result;}
Unfortunately this solution also requires .NET framework 3.5 or later as HashSet was not added until that version. You could also use array.Distinct(), which is a feature of LINQ.
不幸的是,这个解决方案还需要。net framework 3.5或更高版本,因为HashSet是在那个版本之前没有添加的。您还可以使用array.Distinct(),这是LINQ的一个特性。
#3
11
If you needed to sort it, then you could implement a sort that also removes duplicates.
如果您需要对它进行排序,那么您可以实现同样可以删除重复的排序。
Kills two birds with one stone, then.
一举两得。
#4
8
This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:
这可能取决于您希望设计解决方案的程度——如果数组永远不会那么大,而且您不关心排序列表,那么您可能希望尝试以下类似的方法:
public string[] RemoveDuplicates(string[] myList) { System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in myList) if (!newList.Contains(str)) newList.Add(str); return (string[])newList.ToArray(typeof(string)); }
#5
7
The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace.
下面的测试和工作代码将从数组中删除副本。您必须包括系统。集合名称空间。
string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};var sList = new ArrayList();for (int i = 0; i < sArray.Length; i++) { if (sList.Contains(sArray[i]) == false) { sList.Add(sArray[i]); }}var sNew = sList.ToArray();for (int i = 0; i < sNew.Length; i++) { Console.Write(sNew[i]);}
You could wrap this up into a function if you wanted to.
如果你愿意,你可以把它打包成一个函数。
#6
6
-- This is Interview Question asked every time. Now i done its coding.
这是每次面试的问题。现在我完成了它的编码。
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(); }
#7
5
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 "); }}
#8
5
List<String> myStringList = new List<string>();foreach (string s in myStringArray){ if (!myStringList.Contains(s)) { myStringList.Add(s); }}
This is O(n^2), which won't matter for a short list which is going to be stuffed into a combo, but could be rapidly be a problem on a big collection.
这是O(n ^ 2),不重要的名单将被塞进一个组合,但可以迅速成为一个问题在大集合。
#9
4
Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.
将所有字符串添加到字典中,然后获取Keys属性。这将产生每个唯一的字符串,但不一定是以原始输入的顺序。
If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:
如果您要求最终结果与原始输入的顺序相同,当您考虑每个字符串的第一次出现时,请使用以下算法:
- Have a list (final output) and a dictionary (to check for duplicates)
- 有一个列表(最终输出)和一个字典(检查副本)
- For each string in the input, check if it exists in the dictionary already
- 对于输入中的每个字符串,检查它是否已经存在于字典中
- If not, add it both to the dictionary and to the list
- 如果不是,将它添加到字典和列表中。
At the end, the list contains the first occurance of each unique string.
最后,列表包含每个唯一字符串的第一次出现。
Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.
在构建字典时,一定要考虑文化等因素,以确保正确地处理重音字母的重复。
#10
4
The following piece of code attempts to remove duplicates from an ArrayList though this is not an optimal solution. I was asked this question during an interview to remove duplicates through recursion, and without using a second/temp arraylist:
下面的代码试图从ArrayList中删除重复的内容,但这不是最佳的解决方案。在一次采访中,我被问到这个问题:通过递归删除重复内容,而不使用第二个/临时arraylist:
private void RemoveDuplicate() {ArrayList dataArray = new ArrayList(5); dataArray.Add("1"); dataArray.Add("1"); dataArray.Add("6"); dataArray.Add("6"); dataArray.Add("6"); dataArray.Add("3"); dataArray.Add("6"); dataArray.Add("4"); dataArray.Add("5"); dataArray.Add("4"); dataArray.Add("1"); dataArray.Sort(); GetDistinctArrayList(dataArray, 0);}private void GetDistinctArrayList(ArrayList arr, int idx){ int count = 0; if (idx >= arr.Count) return; string val = arr[idx].ToString(); foreach (String s in arr) { if (s.Equals(arr[idx])) { count++; } } if (count > 1) { arr.Remove(val); GetDistinctArrayList(arr, idx); } else { idx += 1; GetDistinctArrayList(arr, idx); } }
#11
4
Maybe hashset which do not store duplicate elements and silently ignore requests to addduplicates.
可能是hashset不存储重复的元素,并且静默地忽略添加重复的请求。
static void Main(){ string textWithDuplicates = "aaabbcccggg"; Console.WriteLine(textWithDuplicates.Count()); var letters = new HashSet<char>(textWithDuplicates); Console.WriteLine(letters.Count()); foreach (char c in letters) Console.Write(c); Console.WriteLine(""); int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 }; Console.WriteLine(array.Count()); var distinctArray = new HashSet<int>(array); Console.WriteLine(distinctArray.Count()); foreach (int i in distinctArray) Console.Write(i + ",");}
#12
4
Here is a O(n*n) approach that uses O(1) space.
这里有一个O(n*n)方法,它使用O(1)空间。
void removeDuplicates(char* strIn){ int numDups = 0, prevIndex = 0; if(NULL != strIn && *strIn != '\0') { int len = strlen(strIn); for(int i = 0; i < len; i++) { bool foundDup = false; for(int j = 0; j < i; j++) { if(strIn[j] == strIn[i]) { foundDup = true; numDups++; break; } } if(foundDup == false) { strIn[prevIndex] = strIn[i]; prevIndex++; } } strIn[len-numDups] = '\0'; }}
The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ.
上面的散列/linq方法是您在现实生活中通常使用的方法。然而,在面试中,他们通常想要施加一些约束,比如常量空间排除散列或没有内部api——这就排除了使用LINQ的可能性。
#13
3
NOTE : NOT tested!
注意:不是测试!
string[] test(string[] myStringArray){ List<String> myStringList = new List<string>(); foreach (string s in myStringArray) { if (!myStringList.Contains(s)) { myStringList.Add(s); } } return myStringList.ToString();}
Might do what you need...
可能做你需要的……
EDIT Argh!!! beaten to it by rob by under a minute!
编辑啊! ! !一分钟之内被罗伯打败了!
#14
3
Tested the below & it works. What's cool is that it does a culture sensitive search too
测试下面的和它的工作。酷的是它也做文化敏感的搜索
class RemoveDuplicatesInString{ public static String RemoveDups(String origString) { String outString = null; int readIndex = 0; CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo; if(String.IsNullOrEmpty(origString)) { return outString; } foreach (var ch in origString) { if (readIndex == 0) { outString = String.Concat(ch); readIndex++; continue; } if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1) { //Unique char as this char wasn't found earlier. outString = String.Concat(outString, ch); } readIndex++; } return outString; } static void Main(string[] args) { String inputString = "aAbcefc"; String outputString; outputString = RemoveDups(inputString); Console.WriteLine(outputString); }
}
}
--AptSenSDET
——AptSenSDET
#15
3
This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :)
这段代码100%地从一个数组中删除重复的值,就像我使用的一样。你可以把它转换成任何OO语言……:)
for(int i=0;i<size;i++){ for(int j=i+1;j<size;j++) { if(a[i] == a[j]) { for(int k=j;k<size;k++) { a[k]=a[k+1]; } j--; size--; } }}
#16
3
Simple solution:
简单的解决方案:
using System.Linq;...public static int[] Distinct(int[] handles){ return handles.ToList().Distinct().ToArray();}
#17
1
you can using This code when work with an ArrayList
当使用ArrayList时,可以使用此代码
ArrayList arrayList;//Add some Members :)arrayList.Add("ali");arrayList.Add("hadi");arrayList.Add("ali");//Remove duplicates from array for (int i = 0; i < arrayList.Count; i++) { for (int j = i + 1; j < arrayList.Count ; j++) if (arrayList[i].ToString() == arrayList[j].ToString()) arrayList.Remove(arrayList[j]);
#18
1
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;}
#19
0
Below is an simple logic in java you traverse elements of array twice and if you see any same element you assign zero to it plus you don't touch the index of element you are comparing.
下面是一个简单的逻辑,在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; } } }}
#20
0
private static string[] distinct(string[] inputArray) { bool alreadyExists; string[] outputArray = new string[] {}; for (int i = 0; i < inputArray.Length; i++) { alreadyExists = false; for (int j = 0; j < outputArray.Length; j++) { if (inputArray[i] == outputArray[j]) alreadyExists = true; } if (alreadyExists==false) { Array.Resize<string>(ref outputArray, outputArray.Length + 1); outputArray[outputArray.Length-1] = inputArray[i]; } } return outputArray; }