sqlLinq获取更高的RN编号

时间:2014-02-21 11:08:55

标签: sql linq entity-framework

这是我的查询

var sonuc = (from c in cd.Product
                        join pp in cd.Product_Picture_Mapping
                            on c.ID equals pp.ProductID
                        join pcc in cd.Picture
                            on pp.PictureID equals pcc.ID
                         select new ProductViewModel() { PicturePath = pcc.Path, ProductID = c.ID }).OrderBy(x => x.ProductID).ToList().AsEnumerable().Select((entry, index) => new ProductViewModel()
                         {
                             PicturePath = entry.PicturePath,
                             ProductID = entry.ProductID
                         }).OrderBy(x => x.ProductID).GroupBy(x => x.ProductID).Select(g => new { g, count = g.Count() })
            .SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) => new { j.ProductID, j.PicturePath, rn = i }));

和OUTPUT;

PicturePath   ProductID RN
samplepath1    4         1
samplepath2    5         1
samplepath3    10        1
samplepath4    10        2
samplepath5    10        3

所以,我想让更高RN拥有相同产品ID的一行,就像这样。

PicturePath   ProductID RN
samplepath1    4         1
samplepath2    5         1
samplepath5    10        3

我怎么能这样? 谢谢

1 个答案:

答案 0 :(得分:3)

按产品ID分组,并从每个组中选择具有最大RN的项目:

var result = from x in sonuc
             group x by x.ProductID into g
             select g.OrderByDescending(x => x.RN).First();