I'm trying to find an item in a list of values based on another value using a lambda expression using the Find method. In this example I'm expecting to get back -1000, but for the life of me, I just can't come up with the proper lamda expression. If that sounds confusing I hope the code and comments below explain it better. TIA.
using System;
using System.Collections.Generic;
namespace TestingStuff {
class Program {
static void Main(string[] args) {
double amount = -200;
//The Range of values
List<MyValue> values = new List<MyValue>();
values.Add(new MyValue(-1000));
values.Add(new MyValue(-100));
values.Add(new MyValue(-10));
values.Add(new MyValue(0));
values.Add(new MyValue(100));
values.Add(new MyValue(1000));
//Find it!!!
MyValue fVal = values.Find(x => (x.Value > amount) && (x.Value < amount));
//Expecting -1000 as a result here since -200 falls between -1000 and -100
//if it were -90 I'd expect -100 since it falls between -100 and 0
if (fVal != null)
Console.WriteLine(fVal.Value);
Console.ReadKey();
}
}
public class MyValue {
public double Value { get; set; }
public MyValue(double value) {
Value = value;
}
}
}
Mmm let me put my intentions a little clearer by specifying all the expected results.
-1000 and less to -101 should give -1000
-100 to - 11 should give -100
-10 to -1 should give -10
0 to 9 should give 0
10 to 99 should give 10
100-999 should give 100
1000 or more should give 1000
This should work:
values.FindLast(x => amount >= x.Value);
You did a logical mistake ... a value can't be > -200 AND < -200 at the same time .. U need the OR expression ( "||" )
MyValue fVal = values.Find(x => (x.Value > amount) || (x.Value < amount));
But if you expect to get -1000 this expression is also wrong
MyValue fVal = values.Find(x => (x.Value < amount));
Because -1000 is SMALLER than -200
EDIT : Ok I think I missunderstood your intention. But the way you want to select your value doesn't seem logical to me. Do you want the next smaller value ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With