c# Find value in a range using lambda

Posted by n4rzul on Stack Overflow See other posts from Stack Overflow or by n4rzul
Published on 2010-05-21T11:25:51Z Indexed on 2010/05/21 11:30 UTC
Read the original article Hit count: 144

Filed under:
|
|
|

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;
        }        
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about find