.NET List.Distinct
Asked Answered
C

4

13

I'm using .NET 3.5. Why am I still be getting:

does not contain a definition for 'Distinct'

with this code:

using System.Collections.Generic;

       //.. . . . . code


    List<string> Words = new List<string>();
       // many strings added here . . .
    Words = Words.Distinct().ToList();
Caracara answered 16/7, 2009 at 16:44 Comment(0)
A
40

Are you

using System.Linq;

?

Distinct is an extension method defined in System.Linq.Enumerable so you need to add that using statement.

And don't forget to add a reference to System.Core.dll (if you're using VS2008, this has already been done for you).

Agnola answered 16/7, 2009 at 16:45 Comment(7)
Is there a reason for naming it like that?Agnola
Martinho -- naming what like what?Pendentive
System.Core. It's mainly extensions... So why Core?Agnola
Ah. No particularly good reason that I'm aware of. What would you have named it?Pendentive
I'm not very good at names, but I think Core is counter-intuitive, since there are a lot of extensions in there. It's not really that important, though. I was just curious about it.Agnola
I would imagine that "Core" here means "something that should really be in mscorlib, but we couldn't put it there for backcompat reasons" :)Barde
@Pavel: That sounds more like it.Agnola
P
8

You forgot to add

using System.Linq;

Distinct is an extension method that is defined in System.Linq.Enumerable, so you can only call it if you import that namespace.

You'll also need to add a reference to System.Core.dll.
If you created the project as a .Net 3.5 project, it will already be referenced; if you upgraded it from .Net 2 or 3, you'll have to add the reference yourself.

Palestine answered 16/7, 2009 at 16:47 Comment(0)
U
2

From msdn blog: Charlie Calvert MSDN Blog Link

To use on .net fiddle : --project type: Console

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var listA = new List<int> { 1, 2, 3, 3, 2, 1 };
        var listB = listA.Distinct();

        foreach (var item in listB)
        {
            Console.WriteLine(item);
        }
    }
}
// output: 1,2,3
Unseasoned answered 17/5, 2017 at 20:22 Comment(0)
T
-1
 List<string> words  = new List<string>();

 // many strings added here . . .

 IEnumerable <string> distinctword  =Words .distinct();

 foreach(string index in distinctword )
 {
      // do what u want here . . .
 }
Theophylline answered 9/12, 2010 at 12:56 Comment(1)
Providing a fix does not answer question "Why".Backwoodsman

© 2022 - 2024 — McMap. All rights reserved.