2012-10-11 103 views
1

我試圖將以下SQL轉換爲Linq,但在嘗試應用min時遇到困惑。基本上我有一個包含梁和他們允許的載荷的桌子。然後我查詢數據庫並按類型查找最小的梁,它具有所需的強度。下面的T-SQL如何將此SQL轉換爲LINQ

select 
    sed.SEDetailID 
from 
    dbo.StructuralElementDetail sed 
    inner join (select StructuralElementID, min(Ix) as MinIX from dbo.StructuralElementDetail where Ix >= @iRequired group by StructuralElementID) o 
     on sed.StructuralElementID = o.StructuralElementID 
      and sed.Ix = o.MinIX 
order by 
    StructuralElementID, 
    Sequence; 

通過其中它們具有所需的強度類型返回最小束。

我已經把梁加載到一個由他們的ID鍵入的字典中,所以我認爲我應該能夠查詢該對象而不是再次調用數據庫。

我的字典是

Dictionary<int, Beam>; 

我想是這樣的,但感到困惑如何我得到的只是每種類型的最小束。

  var Beams = db.Values.Where(specificBeam => specificBeam.Ix >= iRequired) 
       .GroupBy(specificBeam => specificBeam.ElementType) 
        .Select(sb => new { sb.Key, MinIActual = sb.Min(specificBeam => specificBeam.Ix) }); 

任何指針?我可以嵌套第一個結合

回答

2

這已經在LINQPad示例here中進行了測試。

var smallestBeamForTypes = 
    from anyBeam in db.Values 
    where anyBeam.Ix >= iRequired 
    group anyBeam by anyBeam.ElementType into beamTypeGroup 
    let minIx = beamTypeGroup.Min(beam => beam.Ix) 
    select new { 
     ElementType = beamTypeGroup.Key, 
     SmallestBeam = beamTypeGroup.First(beam => beam.Ix == minIx) 
    }; 

然後,您可以遍歷像這樣:

foreach(var smallestBeamForType in smallestBeamForTypes) 
{ 
    Console.WriteLine("For the element type {0} the smallest beam is {1}", 
     smallestBeamForType.ElementType, smallestBeamForType.SmallestBeam); 
} 
+0

嗨,它沒有像beamTypeGroup.Min,但我把它應用到beamTypeGroups,現在我會加入到原始列表。它也重複每個光束> iRequired。它會返回相同的光束,只是多次。 –

+0

檢查我的更新的答案,我已經在LINQPad中測試過它,它似乎對我有用 – Lukazoid

+0

這是我測試過的LINQPad程序的鏈接:http://pastebin.com/3LbqK3Kz – Lukazoid