Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last in LINQ list

Tags:

asp.net

linq

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

like image 394
John Avatar asked Mar 27 '13 13:03

John


People also ask

What is LastOrDefault in LINQ C#?

LastOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the last element of a sequence, or a specified default value if the sequence contains no elements. LastOrDefault<TSource>(IEnumerable<TSource>) Returns the last element of a sequence, or a default value if the sequence contains no elements.


1 Answers

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);
like image 172
Ufuk Hacıoğulları Avatar answered Oct 24 '22 22:10

Ufuk Hacıoğulları