简体   繁体   中英

How to find Maximum Number from a String Array

I have a column named 'Code' which is stored in 'varchar' data type in SQL. I want to find Maximum code from the array.

So,whenever user wants to add a new item,the program will automatically generate the new code.

It was working fine till number 9.But as I added '10' in the code,it is still considering number '9' as the maximum.And showing again number '10' for the new item.

Retrieving the Code Column in a string Array

string commandString = "SELECT Distinct Code FROM Main_Family";
                combobxMCode.Items.Clear();//first clear previous items then refill
                // MessageBox.Show(commandString);
                SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
                sqlCon.Open();
                SqlDataReader dr = sqlCmd.ExecuteReader();
                while (dr.Read())
                {
                    i = 1;
                   // Description = dr["Description"].ToString();
                    combobxMCode.Items.Add(dr[0]);
                    MCode = new string[] {dr["Code"].ToString()};


                }
                dr.Close();

Finding Maximum Code and then showing new Available Code

int[] IntCode = Array.ConvertAll(MCode, int.Parse);
        string MaxCode = (MCode.Max()).ToString();
        Next_Code = int.Parse(MaxCode.ToString());
        int show_code = Next_Code + 1;
        combobxMCode.Text = show_code.ToString();

It is declaring maximum code as 9.Where there are 10 and 11 also present in the array.

How should I retrieve real maximum number from the array?

If you only need the biggest number then you can just rewrite your query to something like this :

string commandString = "SELECT MAX(CAST(Code as INT)) FROM Main_Family";

Then all you have to do is call ExecuteScalar() on your SqlCommand object and cast the result to int .


To explain it in a more detailed way, SELECT MAX() will select only the biggest value queried while CAST([column/value] as [datatype]) will cast it from one datatype to another specified within [datatype] .

Then as you can guess, SELECT MAX() will return only one, the biggest value so you just have one row with one column returned. Meaning that you can call ExecuteScalar() which retrieves the first cell from the first row of the resulting table.

Since you've cast your result from varchar(n) to int you can easily do the same with the result of the ExecuteScalar() and thus get an integer as a result.


// modified query to get the biggest value
string commandString = "SELECT MAX(CAST(Code as INT)) FROM Main_Family";
combobxMCode.Items.Clear();
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();

If you're 100% sure that this table contains data and the result will be not null then use this :

int result = (int)sqlCmd.ExecuteScalar();

But if there could be no values at all in the table then you should probably make some security check:

int? result = sqlCmd.ExecuteScalar() as int?;
if(result.HasValue)
{
    return result.Value;
}
return -1;

Your MCode.Max() call tries to get the maximum value from the MCode array (by the way, variables should start with a lowercase letter, not an uppercase). The thing is, the MCode array is not an array of integers, so the maximum value that is returned is not the maximum integer, but instead the maximum string . Strings are not compared like integers are, so "9" is thought of as the "biggest" string in the array, so that is the one that is returned. Your MCode should be an int array instead of a String array, so that the values are compared as you want them to be, and you get the right result.

Edit: Now that I re-read your code, it seems you are also assigning a new fresh array at each iteration of the loop. If I'm not mistaken, the call

MCode = new string[] {dr["Code"].ToString()};

makes it so that MCode is never assigned more than 1 value. It only retains the last value. You should instead use a List and add to it at each iteration of the loop.

Besides, there are more efficient and quicker ways of getting this info, as m.rogalski pointed out.

Convert MCode to int before taking Max, this would help :

string MaxCode = (MCode.Select(v => int.Parse(v)).Max()).ToString();

像这样

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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