2009-07-16 24 views
9

我正在使用.NET 3.5。爲什麼我仍然會得到:.NET List.Distinct

不包含 '獨特'

與此代碼的定義:

using System.Collections.Generic; 

     //.. . . . . code 


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

回答

35

using System.Linq; 

Distinct是在System.Linq.Enumerable中定義的擴展方法,因此您需要添加using語句。

並且不要忘記添加對System.Core.dll的引用(如果您使用的是VS2008,這已經爲您完成了)。

+0

+1 System.Core程序 – 2009-07-16 16:53:27

+1

是否有將其命名理由像那樣? – 2009-07-16 16:55:30

5

你忘了添加

using System.Linq; 

Distinct是在System.Linq.Enumerable定義的extension method,所以你只能把它如果導入命名空間。

您還需要添加對System.Core.dll的引用。
如果您將該項目創建爲.Net 3.5項目,則該項目將被引用;如果您從.Net 2或3升級它,則必須自己添加參考。

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

從MSDN博客:查理·卡爾弗特MSDN Blog Link

要在.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