2010-07-23 41 views
4

比方說,我有一個具有一堆股票行情LINQ查詢抓鬥最早進入每其他價值

TableQuotes 
2010-07-22 09:45:00.000, "ABC", 102.23 
2010-07-22 09:45:00.000, "EFG", 24.65 
2010-07-22 09:45:00.000, "HIJ", 14.20 
2010-07-22 10:45:00.000, "ABC", 104.25 
2010-07-22 10:45:00.000, "EFG", 26.09 
2010-07-22 10:45:00.000, "HIJ", 12.43 
2010-07-23 09:45:00.000, "ABC", 101.23 
2010-07-23 09:45:00.000, "EFG", 23.65 
2010-07-23 09:45:00.000, "HIJ", 16.20 
2010-07-23 10:45:00.000, "ABC", 99.26 
2010-07-23 10:45:00.000, "EFG", 22.09 
2010-07-23 10:45:00.000, "HIJ", 11.43 
... 

我想知道如何編寫一個查詢的數據庫:
1.抓鬥只有一個股票每個符號的報價每天
2.抓鬥每一天的最早的股票報價的每個符號

因此,舉例來說,從我的示例表所期望的結果將是:

Result 
2010-07-22 09:45:00.000, "ABC", 102.23 
2010-07-22 09:45:00.000, "EFG", 24.65 
2010-07-22 09:45:00.000, "HIJ", 14.20 
2010-07-23 09:45:00.000, "ABC", 101.23 
2010-07-23 09:45:00.000, "EFG", 23.65 
2010-07-23 09:45:00.000, "HIJ", 16.20 

回答

8
var result = from tq in TableQuotes 
group tq by new {tq.TimeStamp.Date, tq.Symbol} into g 
select g.OrderBy(tq => tq.TimeStamp).First(); 
+0

你打我吧;) – 2010-07-23 21:48:18

+0

咦?這看起來不像每個日期只會拉一個符號。 – PatrickSteele 2010-07-23 22:01:17

+0

這是不是隻能抓住任何公司的最早報價,而不是每家公司? – sgriffinusa 2010-07-23 22:02:40

0

這是搞清楚如何寫你的願望http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

LINQ查詢下面是他們給了你的情況,例如直拷貝一個巨大的資源

var categories = 
    from p in products 
    group p by p.Category into g 
    select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) }; 
+0

這種代碼模式叫做什麼:「p => p.UnitsInStock」 – sooprise 2010-07-23 21:49:08

+0

這就是所謂的lambda表達式。 – recursive 2010-07-23 21:50:17

+0

匿名委託,在這種情況下使用lambda語法。要獲得更完整的答案,請點擊此處 - > http://stackoverflow.com/questions/978063/anonymous-delegates-in-c – JupiterP5 2010-07-23 21:52:52

0

下面將返回所請求的解決方案,即每個公司在特定日期的最早報價。

var results = from q in quotes 
       group q by new { q.Symbol, q.TimeStamp.Date } into c 
       select new TableQuote() 
       { 
        Symbol = c.Key.Symbol, 
        TimeStamp = c.Min(ct => ct.TimeStamp), 
        Quote = c.OrderBy(ct => ct.TimeStamp).First().Quote 
       };