List<Of T> Distinct in .NET 3.0?

683 views Asked by At

NET 3.0.

Is there a Distinct on List(Of T)? What packages would I need to import?

If not, is there an equivalence?

4

There are 4 answers

0
Dave Markle On BEST ANSWER

No, you would have to roll your own, or change your project to .NET 3.5 or 4.0.

0
devdigital On

In .NET 3 you would have to roll your own. If you have a look at Remove duplicates from a List<T> in C#, there is an implementation of Distinct for .NET 2 from Keith which uses HashSet.

This is part of the System.Core assembly, so you would need to reference that in your project, which would mean installing the .NET 3.5 framework, but as .NET 3.5 runs on the same version of the CLR, you won't get any issues doing this. When you deploy, you'll need to ensure that either the .NET 3.5 framework is installed on the client machine, or you include System.Core.dll in your release directory.

4
Ani On

In .NET 3.0, one option would be to use a Dictionary<,> with dummy values. E.g. (doesn't handle nulls):

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

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

ICollection<Foo> distinctFoos = dict.Keys;

If you don't like this 'hack', you'll have to roll your own set class.

EDIT: Here's a version that handles nulls in the source:

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
MarkJ On

LinqBridge will allow you to target .Net 3.0 but still use Linq. That includes the Distinct extension method on IEnumerable(Of T).