C# Linq to SQL capers

Associate
Joined
6 Jul 2003
Posts
2,075
Can't figure this out, perhaps someone could help me?

I'm trying to compare a number to the first record in a sorted iqueryable of numbers. The problem is my query is being returned as an iqueryable of numbers, so I can't compare the 2 (a decimal with an iqueryable<decimal>). How do I break the iqueryable down into a single object? I thought [.Take1] would do it but obviously that just gives you an iqueryable with 1 record.

Here's my code (probably horrible for more experienced eyes!)

PHP:
if (IndividualPrice.Total == (from HighestPrice in Model.retailersProducts.Where(x => x.ProductId == product.ProductId) orderby HighestPrice.Total descending select HighestPrice.Total).Take(1))

IndividualPrice.Total is a decimal. I'm an amateur so if there's a better way to do what I'm trying please let me know.
 
Instead of .Take(1) use .First() - this will return a single item rather than a list of 1. It'll throw an error, though, if your query returns no results. You could also use .FirstOrDefault() which won't throw an error if the query has no results, but will return null which will still cause an error in your equality test.
 
Instead of .Take(1) use .First() - this will return a single item rather than a list of 1. It'll throw an error, though, if your query returns no results. You could also use .FirstOrDefault() which won't throw an error if the query has no results, but will return null which will still cause an error in your equality test.

You could use .FirstOrDefault() in combination with DefaultIfEmpty to avoid a null being returned.
 
Back
Top Bottom