2011-06-01 95 views

回答

3
using System.Linq; 
... 
var output = array.Distinct().ToArray(); 

没有LINQ:

int[] array = new[] { 0, 2, 2, 8, 4, 6, 1, 0, 4 }; 

List<int> result = new List<int>(); 
foreach (int element in array) 
{ 
    if (!result.Contains(element)) 
     result.Add(element); 
} 
int[] resultArray = result.ToArray(); 
+0

如果我可以在Visual Studio 2.0中做同样的事情,那么就没有像LINQ这样的概念,那么我该怎么办? – 2011-06-01 12:13:55

+0

'Contains','Add'和'ToArray'是LINQ扩展。 – Edgar 2011-06-01 12:24:05

+0

@埃德加:你确定吗?我将Framework切换到2.0,从列表中删除Linq并编译并运行正常。检查System.Collections.Generic.List 。它包含'Contains','Add'和'ToArray'方法。 – Episodex 2011-06-01 12:26:43

6

您可以使用LINQ并执行myArray.Distinct().ToArray()

+0

如果我可以在Visual Studio 2.0中做同样的事情,那么在那里没有像LINQ这样的概念,所以我能做什么? – 2011-06-01 12:13:21

+0

你的意思是.NET 2.0,对不对?如果没有LINQ,你必须编写自己的方法来筛选数组中的变量,并将它们添加到一个新的数组中,如果那个变量没有变量的话。该方法将返回新的唯一数组。 – Edgar 2011-06-01 12:17:12

+0

请提供我常用的解决方案,用于任何版本的ASP.NET – 2011-06-01 12:17:25

1

这里是一个要在.NET2和C#2正常工作的方法。

(由于HashSet<T>类不可用.NET2它采用了Dictionary<K,V>而不是为effiicient O(1)键查找,忽略值。)

int[] input = new int[] { 0, 2, 2, 8, 4, 6, 1, 0, 4 }; 

int[] output = DistinctItems(input); // 0, 2, 8, 4, 6, 1 

// ... 

public static T[] DistinctItems<T>(T[] input) 
{ 
    Dictionary<T, bool> dict = new Dictionary<T, bool>(input.Length); 

    return Array.FindAll(input, delegate(T item) 
            { 
             if (dict.ContainsKey(item)) 
              return false; 

             dict.Add(item, true); 
             return true; 
            }); 
} 
0

如果你不想让多个条目同样的价值,你应该使用HashSet<T>。就像那样,当你添加一个元素(如果它已经存在的话)的时候直接检测。但这取决于你的需求...