2009-07-30 105 views
3

我使用C#+ VSTS2008 + .Net 3.0。我有一個輸入作爲字符串數組。我需要輸出數組的唯一字符串。任何想法如何有效地實現這一點?例如,我輸入了{「abc」,「abcd」,「abcd」},我想要的輸出是{「abc」,「abcd」}。如何從C#中的集合中獲取唯一值?

+0

問題標題有點誤導。它可能應該是「如何在C#中獲得唯一的集合」。 – angularsen 2013-01-12 09:32:11

回答

19

使用LINQ:

var uniquevalues = list.Distinct(); 

,給你一個IEnumerable<string>

如果你想要一個數組:

string[] uniquevalues = list.Distinct().ToArray(); 

如果你沒有使用.NET 3.5,這是一個有點複雜:

List<string> newList = new List<string>(); 

foreach (string s in list) 
{ 
    if (!newList.Contains(s)) 
     newList.Add(s); 
} 

// newList contains the unique values 

另一種解決方案(也許有點快) :

Dictionary<string,bool> dic = new Dictionary<string,bool>(); 

foreach (string s in list) 
{ 
    dic[s] = true; 
} 

List<string> newList = new List<string>(dic.Keys); 

// newList contains the unique values 
+0

對不起,我錯了。我正在使用.Net 3.0,不能使用LINQ,任何解決方案? – George2 2009-07-30 11:05:14

+0

感謝Philippe,我喜歡你的回覆! – George2 2009-07-30 11:35:38

9

Another opti上是使用HashSet

HashSet<string> hash = new HashSet<string>(inputStrings); 

我想我還去使用LINQ,但它也是一種選擇。

編輯:
您已經更新問題3.0,也許這將幫助: Using HashSet in C# 2.0, compatible with 3.5

2

你可以使用LINQ去了短暫的甜蜜,但如果你不想要嘗試LINQ第二選項的HashSet

選項1:

string []x = new string[]{"abc", "abcd", "abcd"};  
IEnumerable<string> y = x.Distinct();  
x = Enumerable.ToArray(y); 

選項2:

HashSet<string> ss = new HashSet<string>(x); 
x = Enumerable.ToArray(ss);