user793468
user793468

Reputation: 4976

Error when aggregating in linq query

I want to output linq results to an IEnumerable list but I get a cast error:

IEnumerable<vwHour> Total = (from p in vwHours.Where(ph => ph.UserName == UserName())
                                 group p by p.Date into g
                                 select new {Date = g.Key.Value.ToString("mm/dd/yy"), Total = g.Sum(p => p.Hours),});

Error Message:

Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<UI.Models.vwHour>'. An explicit conversion exists (are you missing a cast?)

Am I missing anything here?

Upvotes: 0

Views: 69

Answers (2)

Igby Largeman
Igby Largeman

Reputation: 16747

You're trying to put a list of an anonymous type into a variable for a list of vwHour.

If you wanted to return a list of an anonymous type, you can simply change the variable type to var:

var Total = (  ...

If you really want this query to return a list of vwHour, you need to modify the select:

select new vwHour {  ...

But this requires that vwHour has a Total property and a string Date property. But we can see from the group by and select clauses that your vwHour type has already a Date property which seems to be a Nullable<DateTime>. So there is no way the select will work if you change it to create vwHours.

If your vwHour class is something like this:

class vwHour
{
    public object UserName { get; set; }
    public DateTime? Date { get; set; }
    public int Hours { get; set; }
}

Then this would work:

IEnumerable<vwHour> Total = 
    (from p in vwHours.Where(ph => ph.UserName == UserName())
     group p by p.Date into g
     select new vwHour { Date = g.Key, Hours = g.Sum(p => p.Hours), });

Upvotes: 1

EZI
EZI

Reputation: 15364

IEnumerable<vwHour> Total = (from p in vwHours.Where(ph => ph.UserName == UserName())
                             group p by p.Date into g
                             select new vwHour(){ //<----
                                          Date = g.Key.Value.ToString("mm/dd/yy"), 
                                          Total = g.Sum(p => p.Hours)
                                        });

Upvotes: 2

Related Questions