2012-10-11 104 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