Effective way to determine if more than one element exists using linq.js

I am looking for an efficient way to use linq.js to determine if a collection has more than one distinct value. I assume that the following approach is inefficient, as it should take into account the entire collection.

if (Enumerable.From(collection).Distinct().Take(2).Count() > 1) { //it not unique, continue loop } 

My question is similar to one: Effective Linq Enumerable 'Count () == 1' test

Is there a more efficient linq.js method? Thanks!

+4
source share
2 answers

If you specifically check to see if a collection contains more than one item, the idiomatic way to write it (IMHO) is to use Skip in combination with Any . Skip the first item, and if there are others in the collection, it has more than one. If it was empty, Skip effectively did nothing, and there would be no other elements in the collection.

In your case, your condition will be:

 if (Enumerable.From(collection).Distinct().Skip(1).Any()) { //it not unique, continue loop } 
+1
source
 var test = collection[0]; if (Enumerable .From(collection) .Skip(1) .Any(function (e) { return e != test; }) ) 

Let me explain this. At least two different elements mean that for any element there is at least one element that is not equal to it. Let me select the first element, you can choose any other, only at first it is more convenient and let it see if there is another number that is not equal to it (except for itself).

0
source

All Articles