Shaun Overton
Shaun Overton

Reputation: 49

Pass property to method for use in LINQ query

I'd like SetCloud() to query a List based on different properties and then store it in a Dictionary.

OpenPosition objects have 3 properties: Entry_Price, Stop_Loss, Take_Profit. This is the hard-coded version for Stop_Loss.

private Dictionary<double, PriceLevel> SetCloud(List<OpenPosition> positions, string currency, int trade_Type)
{
    Dictionary<double, PriceLevel> levels = new Dictionary<double, PriceLevel>();

    var priceLevels = from position in positions // query OpenPosition objects from the List<>
                 group position by position.Stop_Loss into groups
                 select groups;

    //add stuff to the Dicionary

    return levels;
}

I'd like to pass the desired OpenPosition property in the signature so that I can use it in the LINQ query. The bad pseudocode version is

SetCloud(....,int trade_Type, object propertyName)
{
    var priceLevels = from position in positions // query OpenPosition objects from the List<>
                 group position by position.propertyName into groups
                 select groups;
}

I hope that communicates why I'm stuck. I don't know which tools to use to accomplish this. Other posts cover how to query an object for the property names, but a string value doesn't do me any good in a LINQ query.

Upvotes: 0

Views: 1179

Answers (1)

James Curran
James Curran

Reputation: 103485

First off, we can reduce

var priceLevels = from position in positions 
             group position by position.Stop_Loss into groups
             select groups;

to just:

var priceLevels = positions.GroupBy(p => p.Stop_Loss);

From there we can make it:

Func<OpenPosition, int> cond = p => p.Stop_Loss;
var priceLevels = positions.GroupBy(cond);

Now we just have to swap out cond.

The easiest/most flexible, is to make it a parameter to the function:

 private Dictionary<double, PriceLevel> SetCloud(List<OpenPosition> positions, 
                 string currency, int trade_Type, Func<OpenPosition, int> cond)
 {
     var levels = new Dictionary<double, PriceLevel>();
     var priceLevels = positions.GroupBy(cond);

     //add stuff to the Dicionary

     return levels;
 }

It would be called like :

 var dict = SetCloud(positions, "USD", trade_type, p=>p.Stop_Loss);

Upvotes: 1

Related Questions