Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare with previous or next element's properties in List<T> while the compare fields are dynamic?

Tags:

c#

dynamic

linq

I have a class

class MarketData
{
    public double Open {get;set;}
    public double High{get;set;}
    public double Low{get;set;}
    public double Close{get;set;}
}

Now I have created List and filled it with last 30 days data. Here's where I am struggling to find best solution for this. A user can enter conditions manually but in fixed format, the fields can be e.g

Open is Greater Than Previous.Close

High is Less Than Previous.Low

Low is Greater Than Next.High,etc

I am parsing the string conditions to

public enum ConditionComparer { And, Or }

class SimpleCondition
{
    public string Operand1 { get; set; }
    public Operators Operator { get; set; }
    public string Operand2 { get; set; }
    public ConditionComparer Compare { get; set; }
}

Now I have to apply this conditions on the List<MarketData> and get matching results.

I used DynamicQueryable class in bit different scenario where conditions where dynamic and it worked perfectly but now I have to compare record with next or previous record.

like image 975
Dinesh Ahuja Avatar asked Nov 02 '22 08:11

Dinesh Ahuja


1 Answers

The problem to get the two MarketData records to compare is a sliding window problem. If you call

var compare = input.Zip(input.Skip(1), 
                        (a,b) => new Tuple<MarketData, MarketData>(a,b));

you get an IEnumerable<Tuple<MarketData, MarketData>> of all pairs of MarketData. Note that your input is enumerated twice.

Using any framework to build dynamic queries, eg. LinqKit, should then do it. Just write expressions that get an Tuple<MarketData, MarketData> as input. The first item in the Tuple is your "older" item, the second is your "newer" item.

like image 64
okrumnow Avatar answered Nov 09 '22 23:11

okrumnow