C# .NET List.Distinct

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1138848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:09:11  来源:igfitidea点击:

.NET List.Distinct

c#linq.net-3.5extension-methods

提问by Nona Urbiz

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

我正在使用 .NET 3.5。为什么我仍然得到:

does not contain a definition for 'Distinct'

不包含“Distinct”的定义

with this code:

使用此代码:

using System.Collections.Generic;

       //.. . . . . code


    List<string> Words = new List<string>();
       // many strings added here . . .
    Words = Words.Distinct().ToList();

采纳答案by R. Martinho Fernandes

Are you

你是

using System.Linq;

?

?

Distinctis an extension method defined in System.Linq.Enumerableso you need to add that using statement.

Distinct是定义的扩展方法,System.Linq.Enumerable因此您需要添加该 using 语句。

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

并且不要忘记添加对System.Core.dll(如果您使用的是 VS2008,这已经为您完成)。

回答by SLaks

You forgot to add

你忘了添加

using System.Linq;

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

Distinct是在中定义的扩展方法System.Linq.Enumerable,因此只有在导入该命名空间时才能调用它。

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.

您还需要添加对System.Core.dll.
如果您将项目创建为 .Net 3.5 项目,它将已经被引用;如果您是从 .Net 2 或 3 升级的,则必须自己添加引用。

回答by mhhsyria

 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 . . .
 }

回答by daviesdoesit

From msdn blog: Charlie Calvert MSDN Blog Link

来自 msdn 博客:Charlie Calvert MSDN 博客链接

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

.net fiddle上使用:--project 类型:控制台

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