2014-11-21 68 views
0

我想讓SetCloud()根據不同的屬性查詢List,然後將它存儲在Dictionary中。將屬性傳遞給在LINQ查詢中使用的方法

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查詢中對我沒有任何好處。

+0

此線程應該回答你的問題:HTTP:// stackoverflow.com/questions/17678197/linq-grouping-dynamically – 2014-11-21 17:11:12

回答

0

首先,我們可以減少

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); 
+0

謝謝!它像一個魅力。我唯一需要修改的是Func b/c中的int,它們是雙值。 – 2014-11-21 20:17:34

+0

好...我擔心這些屬性有三種不同的類型,這會導致一系列的問題...... – 2014-11-21 20:35:12

相關問題