将属性传递给LINQ查询中使用的方法

时间:2014-11-21 16:58:20

标签: c# linq

我希望SetCloud()根据不同的属性查询List,然后将其存储在Dictionary中。

OpenPosition对象有3个属性:Entry_Price,Stop_Loss,Take_Profit。这是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;
}

我想在签名中传递所需的OpenPosition属性,以便我可以在LINQ查询中使用它。坏伪代码版本是

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

我希望能够说明为什么我会陷入困境。我不知道使用哪些工具来实现这一目标。其他帖子介绍了如何查询对象的属性名称,但是字符串值对LINQ查询没有任何帮助。

1 个答案:

答案 0 :(得分:1)

首先,我们可以减少

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

只是:

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

从那里我们可以做到:

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

现在我们只需换出cond

最简单/最灵活的方法是使其成为函数的参数:

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

它会被称为:

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