檢查字符串數組(列表)元素是否具有不同值的最優雅方法是什麼?檢查字符串數組元素是否具有不同的值
E.g.
string[] myArray = { "one", "one", "two"};
輸出:
假
例如
string[] myArray = { "one", "two", "three" };
輸出:
真正
檢查字符串數組(列表)元素是否具有不同值的最優雅方法是什麼?檢查字符串數組元素是否具有不同的值
E.g.
string[] myArray = { "one", "one", "two"};
輸出:
假
例如
string[] myArray = { "one", "two", "three" };
輸出:
真正
myArray.Distinct().Count() == myArray.Length
如何
string[] myArray = { "one", "two", "three" };
bool result = myArray.Length == myArray.Distinct().Count();
.Distinct()
從列表中刪除dupicate價值 - 所以你只需要COMPAR e初始數組中的項目數量和不同的項目數量。
一種不同的方法,無需使用LINQ:
var test = new HashSet<string>();
foreach (var str in myArray)
{
if (test.Contains(str)) return false;
test.Add(str);
}
return true;
可能執行一些數據組更好。
雖然不是很優雅,但這是我首先想到的。
string[] myArray = { "one", "one", "three" };
bool result = myArray.Length == new HashSet<string>(myArray).Count;
我有點晚了......我想我沒有指定<string>
部分...
我想你的意思是像'myArray.ToHashSet()'。奇怪的是MS沒有添加這樣的標準擴展方法。 –
@Habib它的獨特項目的數量,項目的數量進行比較,這似乎回答了這個問題。 –
哦,男人,我需要咖啡......並休息。 +1 – Habib