tags:

views:

76

answers:

5

I have an SQL table with the following design:

TableSchedule:
Id
Description
ImportedDate

I can import a large number of items and they will all have the same ImportedDate.

How can I write a LINQ query that grabs only the entries with the most recent ImportedDate?

var ResultSchedule =
    from a in Db.TableSchedule
    where a.ImportedDate == (Newest?)
A: 

Try this:

  Select * From Table
  Where ImportedDate  = 
     (Select max(ImportedDate) From Table)

If you need the latest record for each [something] like, say, for each individual customer, then make the siubquery correlated

  Select * From Table t
  Where ImportedDate  = 
     (Select max(ImportedDate) 
      From Table
      Where Customer = t.Customer)
Charles Bretana
+1  A: 

Try This

var ResultSchedule = 
from a in Db.TableSchedule 
where a.ImportedDate == (from item in DB.TableSchedule Select item.ImportedDate).Max() 
Vivek
No. As far as my understaning of LINQ goes, an expression tree gets created which results in only 1 DB Query. If I'm wrong, please let me know.
Vivek
Yes, you are right. I take it back. Nice solution.
Yakimych
A: 

How about this:

var ResultSchedule = from a in Db.TableSchedule
                     let max = Db.TableSchedule.Max(i => i.ImportedDate)
                     where a.ImportedDate == max
                     select a;
StriplingWarrior
Is this method considered a "better practice" than the method suggested by Vivek?
Soo
@Soo - Using `let` could come in handy if you make more comparisons with the `max` value. In that case you won't have to duplicate the longer line.
Yakimych
A: 

You can group the results and order them by date:

var ResultsSchedule = Db.TableSchedule.
                      GroupBy(a => a.ImportedDate).
                      OrderByDescending(g => g.Key).
                      FirstOrDefault().
                      Select(g => g);
Yakimych
That's a clever solution
Soo
A: 

In fluent syntax:

var ResultSchedule = 
    Db.TableSchedule.Where(
       a => a.ImportedDate.Equals(Db.TableSchedule.Max(b => b.ImportedDate))
    );
kevev22