Reputation:
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
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
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):
int iNumber = iContext.DetailsRecords.Select(x => (int?)x.Number).Max() ?? 0;
Enumerable.Max Method (IEnumerable<Int32>)
: InvalidOperationException -
source contains no elements.Enumerable.Max Method (IEnumerable<Nullable<Int32>>)
: If the source sequence is empty or contains only values that are null, this function returns null.Upvotes: 3
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
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
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