我使用C#+ VSTS2008 + .Net 3.0。我有一個輸入作爲字符串數組。我需要輸出數組的唯一字符串。任何想法如何有效地實現這一點?例如,我輸入了{「abc」,「abcd」,「abcd」},我想要的輸出是{「abc」,「abcd」}。如何從C#中的集合中獲取唯一值?
3
A
回答
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
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);
相關問題
- 1. C#中的唯一鍵值集合
- 2. 從兩個Java集合對象中獲取兩個唯一值
- 3. MongoDB從多個集合中獲取唯一字集
- 4. 如何從Meteor集合中返回唯一的集合字段?
- 5. 如何在SQL中獲取唯一值?
- 6. 從列的組合中獲取唯一的哈希值
- 7. 我如何從SQL獲取唯一值
- 8. SQL從選擇中獲取唯一值
- 9. 如何從SQL中提取唯一值?
- 10. VBA從集合中獲取值?
- 11. 如何從集合中獲取Linq?
- 12. 如何從集合中獲取對象?
- 13. 如何從集合中獲取mongodb
- 14. 如何獲取C#中字典值集合的計數
- 15. 使用linq從數據集中獲取唯一值
- 16. 從列獲取唯一值
- 17. 獲取兩組的唯一交集值
- 18. 如何從c#中的組合框中獲取值?
- 19. 如何從C#中使用lambda的集合中獲取最後一行+列
- 20. 如何從共享點列表中獲取唯一值?
- 21. 如何從數組中獲取唯一值?
- 22. 如何從c#中的datalist獲取值?
- 23. 如何從c#中的keycode獲取值?
- 24. 獲取Laravel 5.2中列名稱的唯一值的計數集合
- 25. 如何從集合中獲取密鑰和值VB.Net
- 26. 如何從GAMS的集合中獲取一個元素?
- 27. 如何從子集列表中篩選出唯一的組合
- 28. 如何獲取特定列的值的所有唯一組合
- 29. 如何獲取唯一的值cookie
- 30. 如何獲取C++中的集合中的元素?
問題標題有點誤導。它可能應該是「如何在C#中獲得唯一的集合」。 – angularsen 2013-01-12 09:32:11