Cannot implicitly convert type 'System.Linq.IQ

2019-09-14 22:09发布

问题:

I have the following code:

private GolfManagementEntities db = new GolfManagementEntities();

    public class ThanhToan
    {
        public ThanhToan()
        { }
        public Double Total { get; set; }
        public DateTime date { get; set; }
    }

    public List<ThanhToan> listInvoice(DateTime tuNgay, DateTime denNgay)
    {

       List<ThanhToan> invoice= from i in db.Invoices 
                                where i.Date >= tuNgay && i.Date <= denNgay 
                                group i by i.Date into In 
                                select new ThanhToan { 
                                    date= Convert.ToDateTime(In.Key) , 
                                    Total = Convert.ToDouble(In.Sum(s => s.ExtendedCost))
                               };

       return invoice;

}

And I got this error :

Cannot implicitly convert type 'System.Linq.IQueryable<>to . An explicit conversion exists (are you missing a cast?)

please help me

回答1:

Your query returns IQueryable<THanhToan> but you're trying to return a List<ThanhToan>. There's no implicit conversion available (as per the error message) but you can use the ToList extension method to create a list:

public List<ThanhToan> ListInvoices(DateTime tuNgay, DateTime denNgay)
{

    var query = from i in db.Invoices 
                where i.Date >= tuNgay && i.Date <= denNgay
                group i by i.Date into g
                select new ThanhToan {
                    date = Convert.ToDateTime(g.Key), 
                    Total = Convert.ToDouble(g.Sum(s => s.ExtendedCost))
                };
    return query.ToList();
}

(I've changed your method name to follow .NET naming conventions and make more sense in terms of it returning multiple invoices, not just one. Also note how spreading the query over multiple lines makes it much easier to read.)