How can I combine these two LINQ queries in one?
var maxEndDate = lstDates.Select(s => s.EndDate).Max();
var record = lstDates.Where(s => s.EndDate == maxEndDate).First();
LINQ Join queries. As we know the JOIN clause is very useful when merging more than two table or object data into a single unit. It combines different source elements into one and also creates the relationship between them. Using the join, you can grab the data based on your conditions.
CORRECT ANSWER : Use the Concat method.
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.
LINQ provides you three different ways to write a LINQ query in C# or VB.
MaxBy
is what you are looking for: http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/MaxBy.cs using it like this:
var record = lstDates.MaxBy(a => a.EndDate);
EDIT 1: As Jason pointed out this method is intended to be used only when you are working with LINQ to Objects. If you are querying against a database (and so you are using LINQ to SQL, or whatever) you should consider using a different approach.
Yours seems quite readable but, if it doesn't satisfy you, you could always call AsEnumerable
on the IQueryable
object and then use MaxBy
method.
var record = lstDates.AsEnumerable().MaxBy(a => a.EndDate);
EDIT 2: One thing you could change in your query is the second statement. Try to shorten it as follows (in order to avoid using Where
):
var record = lstDates.First(s => s.EndDate == maxEndDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With