Reputation: 10648
I have two lists of floats and both with the same size, for example:
List<float> list1 = new List<float>{ 2.1, 1.3, 2.2, 6.9 }
List<float> list2 = new List<float>{ 2.5, 3.3, 4.5, 7.8 }
Using LINQ I would like to check if all items in list1 are less or equal than those in list2, for example:
2.1 <= 2.5
1.3 <= 3.3
2.2 <= 4.5
6.9 <= 7.8
In this case I want to obtain true as result as all items in list1 are <= items in list2. What is the best efficient way to do it?
Upvotes: 2
Views: 903
Reputation: 1500535
It sounds like you want Zip
, if you really want to compare these pairwise. (It's not true to say that all items in list1
are smaller than all items in list2
, as 6.9 is greater than 2.5 for example.)
Using Zip
:
bool smallerOrEqualPairwise = list1.Zip(list2, (x, y) => x <= y)
.All(x => x);
Or:
bool smallerOrEqualPairwise = list1.Zip(list2, (x, y) => new { x, y })
.All(pair => pair.x <= pair.y);
The first option is more efficient, but the second is perhaps more readable.
EDIT: As noted in comments, this would be even more efficient, at the possible expense of more readability (more negatives).
bool smallerOrEqualPairwise = !list1.Zip(list2, (x, y) => x <= y)
.Contains(false);
Upvotes: 7
Reputation: 10427
bool result = Enumerable.Range(0, list1.Count).All(i => list1[i] <= list2[i]);
Upvotes: 0
Reputation: 38179
list1.Zip(list2, (x, y) => new { X = x, Y = y }).
All(item => (item.X <= item.Y))
Upvotes: 0