0

我正在尝试将一些我必须的 sql 转换为一些 linq,并且遇到了一些麻烦。

我有一个包含 3 列的表,我们将其称为 MfrID、CatID 和 Count。

我希望能够为某些方法提供一个 CatID 列表,它将遍历该表,并在该列表中找到包含 CatID 的所有 MfrID 和计数,并将计数加在一起,其中 mfrID 相等,然后对表进行排序由新的 TotalCounts 然后返回前 X 个结果。

我觉得这在代码中得到了最好的解释,这是我正在尝试解决的示例测试

     [TestMethod]
    public void tempFiguringOutLinqQuery()
    {
        //some example data of what a sql table could look like
        var sampleData = new []
            {
                new {MfrId = 1, CatId = 1, MfrCount = 3},
                new {MfrId = 1, CatId = 2, MfrCount = 1},
                new {MfrId = 5, CatId = 1, MfrCount = 2},
                new {MfrId = 5, CatId = 6, MfrCount = 20},
                new {MfrId = 3, CatId = 5, MfrCount = 14},
                new {MfrId = 3, CatId = 2, MfrCount = 7},
                new {MfrId = 3, CatId = 1, MfrCount = 9},
                new {MfrId = 2, CatId = 1, MfrCount = 1}
            }.ToList();

        var catList = new List<int> {1, 2};

        //where CatIDList.Contains(1 or 2), Add MfrCount where MfrIds are equal, then take the top 3 results ordered by mfrCountDescending
        //ughhhhh
        var results = sampleData.Where(w => catList.Contains(w.CatId)).GroupBy(g => g.MfrCount); 

        //expected results
        // { MfrId = 3, MfrCount = 16 }
        // { MfrId = 1, MfrCount = 4 }
        // { MfrId = 5, MfrCount = 2 }
        Assert.Inconclusive();
    }
4

2 回答 2

2

最简单的方法是按制造商 ID 进行分组,然后对每个组应用转换。你快到,只是按错误的字段分组而错过了转换。例如,包括排序和“获得前 3 名”我们会得到:

var results = sampleData.Where(w => catList.Contains(w.CatId))
                        .GroupBy(w => w.MfrId) // Not MfrCount!
                        .Select(g => new { MfrId = g.Key,
                                           MfrCount = g.Sum(x => x.MfrCount) })
                        .OrderByDescending(x => x.MfrCount)
                        .Take(3);

无论如何,实际上有一个过载GroupBy实际上需要一个组投影,但我个人发现阅读Select分离出来的版本更简单。

于 2013-08-02T16:32:08.160 回答
1

MfrId按(将是组键)对过滤后的数据进行分组并计算MfrCount每个组的总和:

var query = from d in sampleData
            where catList.Contains(d.CatId)
            group d by d.MfrId into g
            select new {
               MfrId = g.Key,
               MfrCount = g.Sum(x => x.MfrCount)
            };

var result = query.OrderByDescending(x => x.MfrCount).Take(3);

或流利的语法:

var result = sampleData.Where(d => catList.Contains(d.CatId))
                       .GroupBy(d => d.MfrId)
                       .Select(g => new {
                           MfrId = g.Key,
                           MfrCount = g.Sum(x => x.MfrCount)
                       })
                       .OrderByDescending(x => x.MfrCount)
                       .Take(3);

结果:

{ MfrId = 3, MfrCount = 16 }
{ MfrId = 1, MfrCount = 4 }
{ MfrId = 5, MfrCount = 2 }

编辑:错过了您只需要前 3 个结果,添加Take(3)到查询中。

于 2013-08-02T16:31:55.267 回答