user1108948
user1108948

Reputation:

compare none value by linq

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?

Upvotes: 1

Views: 152

Answers (5)

MikeSmithDev
MikeSmithDev

Reputation: 15797

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();

Upvotes: 0

myermian
myermian

Reputation: 32505

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;

Upvotes: 3

RAS
RAS

Reputation: 3385

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.

Upvotes: 2

D Stanley
D Stanley

Reputation: 152521

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

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

Upvotes: 0

Servy
Servy

Reputation: 203823

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();

Upvotes: 2

Related Questions