2

I have a not nullable field (Num)

class MyTable
{
    //...
    public int Num { get; set; }
    public string Category { get; set; }
    //...
}

want to find maximum Num for Category == "A"

var maxnum = myTable
   .Where(r => r.Category == "A")
   .Max(r => r.Num);

the problem occurred when there wasn't any record of category == "A" . Because the result of Where() is null so the result of Max() will be null but when Num is not nullable the exception occurred.

I can fix it by setting Num as nullable in table design but I don't like this solution while Num should has value and shouldn't be nullable.

Any suggestion? Is there a way that I accept null value for Num while Num is not nullable? or any better query?

AGB
  • 2,230
  • 1
  • 14
  • 21
Hamid
  • 817
  • 1
  • 13
  • 29
  • so if the `Where.(r => r.Category.Equals("A")` part of the query is null, and `Num` isn't nullable, I would expect it to give you an exception since there is no record of `Num` where `Category.Equals("A")`? so look into `DefaultIfEmpty` – Grizzly May 13 '16 at 19:21
  • See [DefaultIfEmpty()](https://msdn.microsoft.com/en-us/library/bb360179(v=vs.100).aspx) – sammarcow May 13 '16 at 19:24

3 Answers3

10
int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                     .Select(x => x.ShoeSize)
                     .DefaultIfEmpty(0)
                     .Max();

See : Max return value if empty query

Community
  • 1
  • 1
Cyril Iselin
  • 596
  • 4
  • 20
  • OK duplicate question! while I couldn't find that question in search, anyway I add some tags to that question maybe helps better search result later. – Hamid May 13 '16 at 19:58
3

Is there a way that I accept null value for Num while Num is not nullable?

Sure you can:

//...
.Max(r => (int?)r.Num);

Every non nullable value can be turned into nullable (but not vice versa). I personally prefer this method (which acually is suggested in the exception message) because it allows me to distinguish between no max value and max value of 0 (zero) or even int.MinValue.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • UP for answering to the additional ask. I think DefaultIfEmpty is better solution for such questions but as you advised it is better if we don't like to get 0 for empty. – Hamid May 13 '16 at 20:10
1

You can try:

var maxnum = myTable
   .Where(r => r.Category == "A")
   .Max(r => r.Num) ?? 0;

Then you can work with the 0 result.

Carlos Toledo
  • 2,519
  • 23
  • 23