簡體   English   中英

Linq to Entities Group By issue

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM