2011-08-11 42 views
2

我有一個linq查詢返回的結果按第一個字母排序。有沒有辦法在該信件所指定的小組之前返回第一個字母?例如;單獨的linq結果通過第一個字母asp.net mvc 3

**A** 
Acountants 
Apothecary 
**B** 
Basketball 
Biscuits 

等等。我嘗試將這些結果分組,

var companyquery = (from c in db.Categories 
          group c by c.Name.Substring(0, 1) 
           into cgroup 
           select new 
           { 
            FirstLetter = cgroup.Key, 
            Names = cgroup 

           }).OrderBy(letter => letter.FirstLetter); 

     return View(companyquery); 

,但得到的錯誤:

"The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType3 1[System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[NewAtAClick.Models.Category]'.'

所以,現在我使用的排序依據,而不是組_成_。這是我的問題;

var companyquery = (from c in db.Categories 
          orderby c.Name.Substring(0, 1) 
          select c); 

這將以alphebetical順序返回它們。我試着說

 letter1 = companyquery.ToString().SubString(0,1) 

然後

 return view(letter1 + companyquery.ToList()); 

但一無所獲。

在此先感謝!

+0

您的組粘貼到代碼應工作正常,但瞭解它不會是直線名單,但部分,即組 –

+0

我已經添加了我使用到組它的代碼。謝謝。 – Dan

回答

6

錯誤說明了一切。你的觀點期望一個IEnumerable<Category>類型的模型,但你通過別的東西(在這種情況下,因爲你正在通過select new { ... }的調用創建一個新的匿名類型)。

相反,你可以聲明一個新的類型:

public class AlphabeticalMapping<T> { 
    public char FirstLetter { get; set; } 
    public List<T> Items { get; set; } 
} 

,改變你的查詢返回:

var companyquery = (from c in db.Categories 
        group c by c.Name.Substring(0, 1) 
        into cgroup 
        select new AlphabeticalMapping<Category>() { 
         FirstLetter = cgroup.Key, 
         Items= cgroup.ToList() 
        }).OrderBy(mapping => mapping.FirstLetter); 

,並更改您的視圖期待IEnumerable<AlphabeticalMapping<Category>>

+0

感謝您的幫助marcin。我是一名初學者,你已經明確了錯誤的含義,而不僅僅是給我答案,這太棒了!我不得不意外離開辦公室,所以我明天會試試這個,並評論我如何繼續。再次感謝! – Dan

+0

我也是剛剛開始使用C#,這真的幫助我了!謝謝。 ' –

1

,如果你試試這個,會發生什麼?

var companyquery = (from c in db.Categories 
         group c by c.Name.Substring(0, 1) 
          into cgroup 
          select new, 
          { 
           FirstLetter = cgroup.Key, 
           Names = cgroup 

          }) 
          .OrderBy(letter => letter.FirstLetter) 
          .ToDictionary(k => k.FirstLetter, e => e.Names); 
+0

'字典'不能保證鍵值對被枚舉的順序,所以這個視圖實際上可能會失去字母順序。 – marcind

+0

@Marcind,好點,但我想我是從錯誤消息的印象,視圖需要一本字典。 – devuxer

+0

@Marcind,看起來你的答案更進一步說,視圖應該有一個'IEnumerable '類型的模型,所以我會鼓勵你的。 – devuxer

相關問題