如何将此SQL转换为LINQ

时间:2012-10-11 22:42:29

标签: c# linq tsql

我正在尝试将以下SQL转换为Linq,但在尝试应用min时感到困惑。基本上我有一张包含Beams及其允许载荷的桌子。然后我查询数据库并按类型查找最小的梁,它具有所需的强度。以下t-SQL

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

任何指针?我可以将第一个与

结合起来

1 个答案:

答案 0 :(得分: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);
}