C#数组去重
比如我们有这样一个数组:
string[] array = { "hello", "world", "hello" };
//去重后的数组
array = { "hello", "world"};
方法一:
/// 方法名:DelArraySame
/// 功能: 删除数组中重复的元素
/// </summary>
/// <param name="TempArray">所要检查删除的数组</param>
/// <returns>返回数组</returns>
public string[] DelArraySame(string[] TempArray)
{
ArrayList nStr = new ArrayList();
for (int i = 0; i < TempArray.Length; i++)
{
if (!nStr.Contains(TempArray[i]))
{
nStr.Add(TempArray[i]);
}
}
string[] newStr = (string[])nStr.ToArray(typeof(string));
return newStr;
}
方法二:
/// <summary>
/// 移除数组中重复数据
/// </summary>
/// <param name="array">需要除重的数组</param>
/// <returns>不重复数组</returns>
public static string[] DelRepeatData(string[] array)
{
return array.GroupBy(p => p).Select(p => p.Key).ToArray();
}
方法三:
string[] array = { "hello", "world", "hello" };
array.Distinct()