LINQ gets highest value and + 1

I am new to LINQ. I would like to know what is the highest value for "Interrogative Position" and I want to increase it by 1 for a new Question and store it in the database from an MVC 4 view.

My db data: (highest position value is 2)

====================
Question  | Position
====================
Q1        |     1
Q2        |     2

      

After adding a new question: (incrementing the highest position (2) + 1)

====================
Question  | Position
====================
Q1        |     1
Q2        |     2
Q3        |     3

      

My code:

var query =
                db.SURV_Question_Model
                .Where(r => r.Question_Survey_ID == viewModel.Survey_ID)
                .GroupBy(r => new { r.Question_Position })
                .Select(grp => grp.OrderByDescending(i => i.Question_Position).FirstOrDefault());

      

After getting the highest value from the query, can I do something like below?

* int i = query.Question_Position + 1 ??? 

      

Rate your guide.

+3


source to share


2 answers


You can use Max

:

var maxId = db.SURV_Question_Model
              .Where(r => r.Question_Survey_ID == viewModel.Survey_ID)
              .Max(x => x.Position);

      



But, if there is no entry, it will throw an exception. Thus, it is better to change the code as:

var maxId = ...Max(x => (int?)x.Position) ?? 0;

      

+4


source


You don't need the GorupBy method, this should be enough:

var maxId =
    db.SURV_Question_Model
    .Where(r => r.Question_Survey_ID == viewModel.Survey_ID)
    .OrderByDescending(x => x.Position)
    .FirstOrDefault());

      



I don't actually know how to use the where clause, I left it anyway.

+1


source







All Articles