[英]Linq to Entities Group By issue
我有一个销售数据库,在CountryCode列中记录销售商品的2个字符的国家/地区代码。 在销售数据库中,没有数量列,基本上每行代表1次销售,以及与该销售相关的信息。
我本来能够展示畅销国家。 这是我提出的linq查询:
List<TopSellingCountries> tsc = (from sale in Sales
where sale.CountryCode != null
group sale by sale.CountryCode into cc
select new TopSellingCountries
{
CountryCode = cc.Select(c => c.CountryCode).FirstOrDefault(),
CountryCount = cc.Count()
}).OrderByDescending(c => c.CountryCount).Take(10).ToList();
当我将其输出到我的View时,我得到一个包含以下信息的表:
CountryCode | CountryCount
US | 196
IE | 168
US | 99
GB | 91
IE | 57
AU | 32
GB | 22
AU | 18
CA | 17
CA | 17
正如您所看到的,它似乎没有按国家/地区代码正确分组。 有没有人有任何想法我怎么能克服这个?
编辑:如果有人需要,以下是View中的代码:
<table class="normal">
<tr>
<th>Country Code</th>
<th>Country Count</th>
</tr>
<% foreach (var item in Model.TopSellingCountries)
{ %>
<tr>
<td><%: item.CountryCode %></td>
<td><%: item.CountryCount %></td>
</tr>
<% } %>
</table>
采用
CountryCode = cc.Key,
代替
CountryCode = cc.Select(c => c.CountryCode).FirstOrDefault(),
修剪CountryCode可以防止这样的问题:
所以:
group sale by sale.CountryCode.Trim() into cc
确保从CountryCode中删除多余的空格
List<TopSellingCountries> tsc = (from sale in Sales
where sale.CountryCode != null
group sale by sale.CountryCode.Trim() into cc
select new TopSellingCountries
{
CountryCode = cc.Key,
CountryCount = cc.Count()
})
.OrderByDescending(c => c.CountryCount)
.Take(10)
.ToList();
请尝试以下方法
List<TopSellingCountries> tsc = (from sale in Sales
where sale.CountryCode != null
group sale by sale.CountryCode into cc
order by cc.Count() descending
select new TopSellingCountries
{
CountryCode = cc.Key,
CountryCount = cc.Count()
}).Take(10).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.