我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
当前回答
这可能取决于你有多想设计解决方案-如果数组永远不会那么大,你不关心排序列表,你可能想尝试类似于下面的东西:
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));
}
其他回答
下面是HashSet<string>方法:
public static string[] RemoveDuplicates(string[] s)
{
HashSet<string> set = new HashSet<string>(s);
string[] result = new string[set.Count];
set.CopyTo(result);
return result;
}
不幸的是,这个解决方案也需要。net框架3.5或更高版本,因为HashSet直到该版本才被添加。你也可以使用array.Distinct(),这是LINQ的一个特性。
注意:未测试!
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();
}
也许能满足你的需要…
编辑啊! !不到一分钟就被抢了!
下面这段代码试图从ArrayList中删除重复项,尽管这不是最佳解决方案。在一次面试中,我被问到通过递归删除重复项,而不使用第二个/temp数组列表:
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);
}
}
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²),这对于一个短列表来说没有什么关系因为它将被塞进一个组合中,但对于一个大的集合来说可能很快就会成为一个问题。