检查字符串数组(列表)元素是否具有不同值的最优雅方法是什么?检查字符串数组元素是否具有不同的值
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