简体   繁体   中英

C# LINQ - Comparing to float lists

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?

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);
list1.Zip(list2, (x, y) => new { X = x, Y = y }).
      All(item => (item.X <= item.Y))
bool result = Enumerable.Range(0, list1.Count).All(i => list1[i] <= list2[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM