1

I have an integer column(not null) in a sql server 2008 database/table, I want to retrieve it.

  // go to the table and get the largest number, if none exists, use 0.
        int iNumber = iContext.DetailsRecords.Max(x => x.Number); // from entity

But at the very beginning, the table is empty. I want to set is as 0. How to change the code?

5 Answers5

3

If you don't want to check if the DetailsRecords is null, but rather handle if the source sequence is empty, then use this answer (I adjusted it a bit differently for your LINQ usage):

Max or Default?


int iNumber = iContext.DetailsRecords.Select(x => (int?)x.Number).Max() ?? 0;

Community
  • 1
  • 1
myermian
  • 31,823
  • 24
  • 123
  • 215
  • 2
    @Servy: Wrong. `Max(IEnumerable)` of an empty sequence throws an exception. `Max(IEnumerable>)` of an empty sequence returns null. The casting is a valid solution (duplicate answer that has been accepted). – myermian Nov 12 '12 at 18:57
2

try this:
int iNumber = iContext.DetailsRecords==null? iContext.DetailsRecords.Max(x => x.Number) : 0;
or
int iNumber = iContext.DetailsRecords.Any()? iContext.DetailsRecords.Max(x => x.Number) : 0; if table is not null and contains 0 records.

RAS
  • 3,375
  • 15
  • 24
  • I'm not sure if that's what he's asking for, but I gave you a +1 in case it is. Though, I have a feeling it's that the DetailsRecords contains no elements. – myermian Nov 12 '12 at 18:48
2

You can use DefaultIfEmpty for this. If the sequence is empty it will return the provided item as the only item in the sequence, if not it will return the original sequence.

IEnumerable<int> numbers = new int [] { };

numbers.DefaultIfEmpty(0).Max();
Servy
  • 202,030
  • 26
  • 332
  • 449
  • 1
    +1, but I suspect this needs to be `iContext.DetailsRecords.Select(x => x.Number).DefaultIfEmpty(0).Max();` – Reed Copsey Nov 12 '12 at 18:50
  • @ReedCopsey Yep, but I didn't think it was too much of a leap for him to get there from what I provided. Not all code answers need to be copy/paste/done to answer the question. – Servy Nov 12 '12 at 18:52
  • Well, I just thought I'd point it out since it actually requires another conceptual addition (the mapping operation via select) in addition to the original + your edit. – Reed Copsey Nov 12 '12 at 18:53
0

Use the Any function to see if there are any records:

int iNumber = iContext.DetailsRecords.Any() 
              ? iContext.DetailsRecords.Max(x => x.Number) 
              : 0;
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

I know this already has an accepted answer, but another good way would just be FirstOrDefault().

int iNumber = iContext.DetailsRecords.OrderByDescending(x => x.Number).FirstOrDefault();

I use this way often and also can let you setup a new object if the result was null.

 MyObject m = mySearch.GetItems.Where(a => a.id == id).FirstOrDefault() ?? new MyObject();
MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89