If you have a string of "1,2,3,1,5,7" you can put this in an array or hash table or whatever is deemed best.
如果你有一个字符串“1,2,3,1,5,7”,你可以把它放在一个数组或哈希表或任何被认为是最好的。
How do you determine that all value are the same? In the above example it would fail but if you had "1,1,1" that would be true.
你如何确定所有的价值是一样的?在上面的例子中它会失败,但如果你有“1,1,1”那将是真的。
5 个解决方案
#1
This can be done nicely using lambda expressions.
这可以使用lambda表达式很好地完成。
For an array, named arr
:
对于名为arr的数组:
var allSame = Array.TrueForAll(arr, x => x == arr[0]);
For an list (List<T>
), named lst
:
对于列表(List
var allSame = lst.TrueForAll(x => x == lst[0]);
And for an iterable (IEnumerable<T>
), named col
:
对于可迭代(IEnumerable
var first = col.First();
var allSame = col.All(x => x == first);
Note that these methods don't handle empty arrays/lists/iterables however. Such support would be trivial to add however.
请注意,这些方法不处理空数组/列表/迭代。然而,这种支持是微不足道的。
#2
Iterate through each value, store the first value in a variable and compare the rest of the array to that variable. The instant one fails, you know all the values are not the same.
遍历每个值,将第一个值存储在变量中,并将数组的其余部分与该变量进行比较。瞬间失败,你知道所有的值都不一样。
#3
How about something like...
怎么样......
string numArray = "1,1,1,1,1";
return numArrray.Split( ',' ).Distinct().Count() <= 1;
#4
I think using List<T>.TrueForAll
would be a slick approach.
我认为使用List
#5
Not as efficient as a simple loop (as it always processes all items even if the result could be determined sooner), but:
不如简单的循环有效(因为它总是处理所有项目,即使结果可以更快地确定),但是:
if (new HashSet<string>(numbers.Split(',')).Count == 1) ...
#1
This can be done nicely using lambda expressions.
这可以使用lambda表达式很好地完成。
For an array, named arr
:
对于名为arr的数组:
var allSame = Array.TrueForAll(arr, x => x == arr[0]);
For an list (List<T>
), named lst
:
对于列表(List
var allSame = lst.TrueForAll(x => x == lst[0]);
And for an iterable (IEnumerable<T>
), named col
:
对于可迭代(IEnumerable
var first = col.First();
var allSame = col.All(x => x == first);
Note that these methods don't handle empty arrays/lists/iterables however. Such support would be trivial to add however.
请注意,这些方法不处理空数组/列表/迭代。然而,这种支持是微不足道的。
#2
Iterate through each value, store the first value in a variable and compare the rest of the array to that variable. The instant one fails, you know all the values are not the same.
遍历每个值,将第一个值存储在变量中,并将数组的其余部分与该变量进行比较。瞬间失败,你知道所有的值都不一样。
#3
How about something like...
怎么样......
string numArray = "1,1,1,1,1";
return numArrray.Split( ',' ).Distinct().Count() <= 1;
#4
I think using List<T>.TrueForAll
would be a slick approach.
我认为使用List
#5
Not as efficient as a simple loop (as it always processes all items even if the result could be determined sooner), but:
不如简单的循环有效(因为它总是处理所有项目,即使结果可以更快地确定),但是:
if (new HashSet<string>(numbers.Split(',')).Count == 1) ...