[英]Linq to Entities Group By issue
I have a sales database that records in a CountryCode column the 2 character country code of where a good was sold. 我有一个销售数据库,在CountryCode列中记录销售商品的2个字符的国家/地区代码。 In the sales database, there is no quantity column, basically every row represents 1 sale, and the information associated with that sale.
在销售数据库中,没有数量列,基本上每行代表1次销售,以及与该销售相关的信息。
I was to be able to display the top selling countries. 我本来能够展示畅销国家。 Here is the linq query I have come up with:
这是我提出的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();
When I output this to my View however, I get a table with the following information: 当我将其输出到我的View时,我得到一个包含以下信息的表:
CountryCode | CountryCount
US | 196
IE | 168
US | 99
GB | 91
IE | 57
AU | 32
GB | 22
AU | 18
CA | 17
CA | 17
As you can see it doesn't seem to be grouping properly by country code. 正如您所看到的,它似乎没有按国家/地区代码正确分组。 Does anyone have any ideas how I can overcome this?
有没有人有任何想法我怎么能克服这个?
EDIT: Here is the code from the View if anyone needs it: 编辑:如果有人需要,以下是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>
use 采用
CountryCode = cc.Key,
instead of 代替
CountryCode = cc.Select(c => c.CountryCode).FirstOrDefault(),
Also trimming the CountryCode can prevent problems like this: 修剪CountryCode可以防止这样的问题:
so: 所以:
group sale by sale.CountryCode.Trim() into cc
Make sure you trim excess spaces off of the CountryCode 确保从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();
Please try with the following 请尝试以下方法
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.