我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。
从c#数组中删除重复项的最佳方法是什么?
当前回答
下面是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的一个特性。
其他回答
你可以使用一个LINQ查询来做到这一点:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
List<String> myStringList = new List<String> (); foreach (myStringArray中的字符串) { 如果(! myStringList.Contains (s)) { myStringList.Add(年代); } }
这是O(n²),这对于一个短列表来说没有什么关系因为它将被塞进一个组合中,但对于一个大的集合来说可能很快就会成为一个问题。
使用Distinct和stringcompararer删除重复和忽略区分大小写。InvariantCultureIgnoreCase
string[] array = new string[] { "A", "a", "b", "B", "a", "C", "c", "C", "A", "1" };
var r = array.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();
Console.WriteLine(r.Count); // return 4 items
strINvalues = "1,1,2,2,3,3,4,4";
strINvalues = string.Join(",", strINvalues .Split(',').Distinct().ToArray());
Debug.Writeline(strINvalues);
不确定这是巫术还是漂亮的代码
1 strINvalues .Split(',').Distinct().ToArray()
2字符串。加入(”、“XXX);
1拆分数组,使用Distinct [LINQ]删除重复项 2 .在没有副本的情况下将其连接回去。
抱歉,我从来没有读过StackOverFlow上的文本,只是代码。它比文本更有意义;)
下面这段代码试图从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);
}
}