Search code examples
c#.netlinq-to-entities

Get an int out of a Linq query instead of string


I'm new to c#, Linq and .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]. 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. (Right now I'm using void because I'm trying to get the right result before returning it)


Solution

  • 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.

    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.

    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. 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.

    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.