Group items with Linq and display in table in MVC

2019-08-29 06:30发布

问题:

I want to be able to display data from a database grouped under categories. The application is an attempt at a timesheet application. The database schema looks like this:

(table) TimeSegments
TimeSegmentID
Hours
Date
ConsultantID (FK)
TaskID (FK)
ProjectID (FK)

(table) Projects
ProjectID
ProjectName

(table) Tasks
TaskID
TaskName

(table) Consultants
ConsultantID
ConsultantName

I can get the data from the model (here called ts) and display it, but I want it to be grouped so that I can show hours by project and task. Here's my attempt so far. I guessed the group statement in Linq would be appropriate, but I don't know if that's correct:

    public IList<TimeSegment> TimeSegmentsByProject
    {
        get
        {
            var projectGroups = from timeSegment in ts.TimeSegments
                                group timeSegment by timeSegment.Project
                                into projectGroup
                                select projectGroup;
            return projectGroups.ToList(); //Doesn't work
        }
    }

Now this fails, because the result can't be converted to a list according to the compiler. I thought this expression would give me a collection of collections, and that I would be able to return this, get it in the controller, and pass it to the view for display. Apparently not.

So how should I go about this? If anyone could show me how to return the correct type, and preferably also give me an example of how a view could receive it and display it categorized by Project, I would really appreciate it!

EDIT:

This doesn't work either (return type suggested by The_Smallest below):

    public IGrouping<Project, TimeSegment> TimeSegmentsByProject
    {
        get
        {
            var projectGroups = from timeSegment in ts.TimeSegments
                                group timeSegment by timeSegment.Project
                                into projectGroup
                                select projectGroup;
            return projectGroups;
        }
    }

The compiler says it cannot convert [blabla] IQueryable to this type (the types are similar, but the return type is IQueryable)

回答1:

After group-by command linq returns IEnumerable<IGrouping<TKey, TValue>>, while you expect it to be IEnumerable<TimeSegment>.
In your example you can change return type of your method from IList<TimeSegment> to IEnumerable<IGrouping<Project, TimeSegment>> where Project is type of timeSegment.Project
PS: You can change IEnumerable to Array or IList (Whichever you want, just don't forget to Add .ToArray() or .ToList())



标签: linq-to-sql