简体   繁体   English

从 Linq 查询中获取 int 而不是字符串

[英]Get an int out of a Linq query instead of string

I'm new to c#, Linq and .NET.我是 c#、Linq 和 .NET 的新手。 I have some code that does a query to get the last record from a table in a database.我有一些代码可以查询以从数据库中的表中获取最后一条记录。 The field that I'm trying to access is an int but when I try to print it I get System.Data.Objects.ObjectQuery`1[System.Int32] .我试图访问的字段是一个 int 但是当我尝试打印它时,我得到System.Data.Objects.ObjectQuery`1[System.Int32] Here's the code:这是代码:

public void getLastProgNumber() 
        {
            using (var db = new IntranetEntities())
            {
                var value = (db.table.OrderByDescending(ai => ai.NumProgHWSW).GroupBy(a => a.NumProgHWSW).Select(g => Convert.ToInt32(g.FirstOrDefault())));
                MessageBox.Show(value.ToString());
            }            
        }

I need to convert it to an int type and return it if possible, thank you.我需要将其转换为 int 类型并尽可能返回,谢谢。 (Right now I'm using void because I'm trying to get the right result before returning it) (现在我正在使用void因为我试图在返回之前获得正确的结果)

If you want to get the last record from the database table, there are multiple ways.如果要从数据库表中获取最后一条记录,有多种方法。 But doing GroupBy is certainly not one of them.但做 GroupBy 肯定不是其中之一。

You can order the rows by doing OrderByDescending so that row with the maximum value of that column positioned at the first and then you can do FirstOrDefault .您可以通过执行 OrderByDescending 对行进行排序,以便该列的最大值位于第一个的行,然后您可以执行FirstOrDefault

var val = db.table.OrderByDescending(ai => ai.NumProgHWSW).FirstOrDefault();
// val is the row with maximum value of NumProgHWSW.
// you can display the value of NumProgHWSW in messagebox by doing following.
MessageBox.Show(val.NumProgHWSW);

If you want to get the Maximum value of NumProgHWSW in a variable directly from the LINQ query.如果要直接从 LINQ 查询中获取变量中NumProgHWSW的最大值。 you can do this by你可以这样做

var val = db.table.OrderByDescending(ai => ai.NumProgHWSW).FirstOrDefault().NumProgHWSW;
MessageBox.Show(val);

You can also use Max LINQ method to get the maximum value without doing OrderByDescending.您也可以使用Max LINQ 方法来获取最大值,而无需执行 OrderByDescending。

var val = db.table.Max(ai => ai.NumProgHWSW);
MessageBox.Show(val);

Using Max is a better approach then above two as it does not order the table rows before data retrieval and that way it works faster when the table has large number of rows.使用Max是一种比上述两种方法更好的方法,因为它不会在数据检索之前对表行进行排序,这样当表有大量行时它的工作速度会更快。

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

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