Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way of combining two LINQ queries

Tags:

c#

linq

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();
like image 327
user424134 Avatar asked Aug 26 '11 17:08

user424134


People also ask

How do I join two queries in LINQ?

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.

How you can merge the results from two separate LINQ queries into a single result set?

CORRECT ANSWER : Use the Concat method.

Is LINQ better than for loop?

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.

How many ways can you write LINQ queries?

LINQ provides you three different ways to write a LINQ query in C# or VB.


1 Answers

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);
like image 80
as-cii Avatar answered Nov 01 '22 22:11

as-cii