列表<of t =“”> .NET 3.0中的区别?</of>

时间:2011-02-09 14:02:50

标签: .net vb.net list .net-3.0

NET 3.0。

Distinct上有List(Of T)吗? 我需要导入哪些包?

如果没有,是否有等价?

4 个答案:

答案 0 :(得分:2)

在.NET 3.0中,一个选项是使用带有虚拟值的Dictionary<,>。例如。 (不处理null s):

List<Foo> foos  = ...
Dictionary<Foo, bool> dict = new Dictionary<Foo, bool>();

foreach(Foo foo in foos)
   dict[foo] = true;

ICollection<Foo> distinctFoos = dict.Keys;

如果你不喜欢这个'hack',你将不得不推出自己的集合类。

编辑:这是在源代码中处理null的版本:

public static IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("source");

    Dictionary<T, bool> dict = new Dictionary<T, bool>();
    bool nullSeen = false;

    foreach (T item in source)
    {
        if (item == null)
        {
            if (!nullSeen)
                yield return item;

            nullSeen = true;
        }

        else if (!dict.ContainsKey(item))
        {
            dict.Add(item, true);
            yield return item;
        }
    }
}

答案 1 :(得分:0)

在.NET 3中,您必须自己动手。如果你看一下Remove duplicates from a List<T> in C#,Keith就会使用HashSet实现Distinct for .NET 2。

这是System.Core程序集的一部分,因此您需要在项目中引用它,这意味着安装.NET 3.5框架,但是当.NET 3.5在相同版本的CLR上运行时,您赢了这样做没有任何问题。部署时,您需要确保在客户端计算机上安装了.NET 3.5框架,或者在发布目录中包含System.Core.dll。

答案 2 :(得分:0)

不,您必须自己动手,或将项目更改为.NET 3.5或4.0。

答案 3 :(得分:0)

LinqBridge将允许您定位.Net 3.0,但仍然使用Linq。其中包括IEnumerable(Of T)上的Distinct扩展方法。