Skip to content Skip to sidebar Skip to footer

How To Limit An Sql Query To Return At Most One Of Something?

I have a table in my database representing releases of software; the relevant columns of the schema being as follows: ProductID int PlatformID tinyint Date datetime All

Solution 1:

I think the following code does what you’re asking for:

var latestProducts = db.Releases
    .GroupBy(p => p.PlatformID)
    .Select(grp =>new {
        Platform = grp.Key,
        Latest = grp.OrderByDescending(p => p.Date).FirstOrDefault()
    })
    .OrderByDescending(entry => entry.Latest.Date);

foreach (var entry in latestProducts)
{
    Console.WriteLine("The latest product for platform {0} is {1}.",
        entry.Platform,
        entry.Latest.ProductID);
}

Here’s how it works:

  • First, take all the products
  • Group them into groups by common PlatformID
  • Within each group, sort the products in that group by date descending and pick the first (that’ll be the one with the latest date)
  • For each group, create an object containing the PlatformID and the platform’s latest Product
  • Sort this list of objects by date descending.

Solution 2:

from plat in 
                (from p in Products
                    group p by p.PlatformID
                )

                let latestRelease = 
                (
                    from p in plat
                    orderby p.Date descendingselect p
                ).FirstOrDefault()

                where latestRelease != nullselectnew 
                {
                    PlatformID = plat.Key,
                    LatestProductID = latestRelease.ProductID,
                    LatestDate = latestRelease.Date
                }

Solution 3:

One line code:

IEnumerable<Product> products = AllProducts.GroupBy(p => p.PlatformID, 
    (pid, source) => source.Where(p => p.PlatformID == pid).OrderByDescending(p => p.Date).FirstOrDefault());

Solution 4:

If you are using LINQ to Entities, LINQ to SQL, etc, then just use First() or FirstOrDefault(), they will be smart enough to limit the query to 1. If you prefer to be more explicit, you can add Take(1) to your query.

Post a Comment for "How To Limit An Sql Query To Return At Most One Of Something?"