简体   繁体   English

LINQ获得最高值和+ 1

[英]LINQ get Highest value and + 1

I'm newbie to LINQ. 我是LINQ的新手。 I will like to get know what's the highest value for 'Question Position' and i want increase it by 1 for new Question and save it into database from MVC 4 view. 我想知道“问题位置”的最高值是什么,我希望将新问题增加1,并将其从MVC 4视图保存到数据库中。

My db data : (highest position value is 2) 我的数据库数据:(最高位置值为2)

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

After added new Question : ( increment the highest position (2) + 1 ) 添加新问题后:(增加最高位置(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 i get the highest value from query, can i do something like below? 在我从查询中获得最高价值后,我可以执行下面的操作吗?

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

Appreciate your guidance. 感谢您的指导。

You can use Max : 您可以使用Max

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

But, if there is not any record it will throw an exception. 但是,如果没有任何记录,它将抛出异常。 So, it will be better to change your code as: 因此,最好将代码更改为:

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

You don't need the GorupBy method, this should be enough: 你不需要GorupBy方法,这应该足够了:

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

I actually don't know the usage of the where condition, I left there anyway. 我实际上不知道where条件的用法,无论如何我都离开了那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM