PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

Lambda functions using defined variables

I would like to test a condition based on values pulled from a configuration file (XML file, FYI). I have something like this to do the checks:

List<Condition> conditions = new List<Condition>();
float fVal;
foreach (XmlAttribute attr in conNode.Attributes)
{
    switch (attr.Name.ToLower())
    {
        case "alt_max":
            fVal = float.Parse(attr.Value);
            conditions.Add((t) => { return t.altitude <= fVal; });
            break;
        case "alt_min":
            fVal = float.Parse(attr.Value);
            conditions.Add((t) => { return t.altitude >= fVal; });
            break;

....

If I had my conditions set up such that both of these conditions were checked, only the last value would survive. IE

<condition alt_max="0.3" alt_min="0"/>

What I want to do is to see if the value (t.altitude in this case) is between 0 and 0.3. What I'm actually doing is testing if the value is identically 0, as it has to be both less than and greater than 0, due to the fact that references are sent to lambda functions. The value fVal in both instances will be 0, so it has to be >=0 and <=0.

I'm really struggling how I can set this up such that I can test my conditions properly. Any suggestions?

Upvotes: 1

Views: 56

Answers (1)

vesan
vesan

Reputation: 3369

Your lambdas are reusing the variable fval, which is defined outside the scope of the foreach.

Moving this line:

float fVal;

inside the foreach should make it work the way you want.

Upvotes: 2

Related Questions