Alex Rivera | Logout

get last in LINQ list

Asked 2013-03-27T13:18:27.497
18
Context db = new Context();
List<Invoice> invoice =
(from LocalInvoice in db.Invoices
where LocalInvoice.Site_Id == this.SiteIdentifier
select LocalInvoice).ToList();

Returns a list of records. I want to select the last in the list. I've tried .ToList().LastOrDefault(); but the error im getting is cannot convert type 'invoice' to 'System.Collections.Generic.List.

Why is it saying this have I not declared invoice as a list List<Invoice> invoice

Any help much appreciated. Ta


EDIT Thanks for the reply everyone i've tried what you all have advised and each time im getting the error: The query operator 'LastOrDefault' is not supported.

Also I havent actually explained what I am trying to do overall which may be causing a problem. I have a table containing all the invoices, each with a seperate 'id'. However each record will have a SiteIdentifier column which is used multiple times for different invoices. So each Site may have multiple invoices.

Trying to get the most recent Invoice for the site. So say invoice

id SiteIdentifier 
73 25
74 25
75 25

I was attempting to get all the records where the SiteIdentifier == this.SiteIdentifier(e.g.25), then get the most recent record which would have beeing invoice id 75.

Anyone have any ideas? Again thanks for all the help

Edit
Report

1 Answer

32

LastOrDefault will return a single element. You shouldn't call ToList without applying a filter first, it would retrieve all the rows from the database while you just need one.

var invoice = db.Invoices.LastOrDefault(s => s.Site_Id == this.SiteIdentifier);

Also you have to apply ordering if you are querying a relational table. LastOrDefault is only meaningful with in-memory collections. Looks like it is not supported in EF and will throw an exception.

Best solution is to inverse the ordering and use FirstOrDefault method:

var invoice = db.Invoices.OrderByDescending(s => s.Id) 
                         .FirstOrDefault(s => s.Site_Id == this.SiteIdentifier);
answered 2013-03-27T13:20:54.830

Your Answer