开发者

Seperate linq results by first letter asp.net mvc 3

I have a linq query which returns results ordered by first letter. Is there a way to return the first letter before the group ordered by that letter? For instance;

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

and so on. I tried grouping my results like this;

  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);

but got error:

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

So now I'm using orderby instead of group _ into _ . Here is my query;

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

This returns them i开发者_运维问答n alphebetical order. I tried saying

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

then

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

But nothing.

Thanks in advance!


The error says it all. Your view expects a model of type IEnumerable<Category> but you passed in something else (in this case because you are creating a new anonymous type via the call to select new { ... }).

Instead you could declare a new type:

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

And change your query to return:

 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);

And change your view to expect IEnumerable<AlphabeticalMapping<Category>>


What happens if you try this?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜