1

我有一个关于我在 LINQ 中编写的查询的查询,希望有人能提供帮助。基本上我有以下(示例数据)

ProductCode  LanguageID   LegislationId   Version
1234         English       UK              1
1234         English       UK              2
5678         English       UK              1
9999         English       UK              1
9999         English       UK              2
9999         Spanish       Spain           1

所以,我需要做的是根据用户提供的条件返回记录,包括 LanguageID 和 Description。这里棘手的部分是,如果有相同产品代码、语言和法规的多个版本,那么我只想返回最新版本。

所以......我的代码如下(pLegislations 包含一个以逗号分隔的立法列表):

List<string> legList = pLegislations.Split(',').ToList();
IEnumerable<MyClass> results = null;

results = (from a in context.ALLProducts
           let prodCode = a.ProductCode
           let prodDesc = a.ProductDescription
           where legList.Contains(a.LegislationID) &&
                 (a.LanguageID == pLanguage || pLanguage == null) &&
                  a.BrandName == pMarket &&
                 (prodCode.Contains(pSearch) || prodDesc.Contains(pSearch) || 
                                                pSearch == string.Empty) &&
                 prodCode[0] != 'x' &&
                ((pMarket == "testMarket") ? prodCode.StartsWith("0") : true)
                select new MyClass
                {
                   BrandName = a.BrandName,
                   BulkCode = prodCode,
                   BulkDescription = prodDesc,
                   Language = a.LanguageName,
                   LanguageCode = a.LanguageID
                }).ToList();

现在这一切在没有多个版本的情况下都可以正常工作,所以我的问题是 - 我如何过滤它以便在 ProductCode、Language 和 Legislation 匹配时只返回最新版本,即如果我要通过 Language = ' English' 和 Legislation = 'UK' 那么我希望得到以下结果:

ProductCode  LanguageID   LegislationId   Version
1234         English       UK              2
5678         English       UK              1
9999         English       UK              2
9999         Spanish       Spain           1

提前致谢

安德鲁

4

1 回答 1

1

按 (1) 对结果进行分组,ProductCode并从具有最大值Version(2) 的每个组项中进行选择:

results = (from a in context.ALLProducts
           let prodCode = a.ProductCode
           let prodDesc = a.ProductDescription
           where legList.Contains(a.LegislationID) &&
                 (a.LanguageID == pLanguage || pLanguage == null) &&
                  a.BrandName == pMarket &&
                 (prodCode.Contains(pSearch) || 
                  prodDesc.Contains(pSearch) || 
                  pSearch == string.Empty) &&
                  prodCode[0] != 'x' &&
                 ((pMarket == "testMarket") ? prodCode.StartsWith("0") : true)
           group a by a.ProductCode into g // 1
           let lastProduct = g.OrderByDescending(x => x.Version).First() // 2
           select new MyClass
                {
                   BrandName = lastProduct.BrandName,
                   BulkCode = prodCode,
                   BulkDescription = prodDesc,
                   Language = lastProduct.LanguageName,
                   LanguageCode = lastProduct.LanguageID
                }).ToList();
于 2013-06-07T10:33:42.370 回答