Click here to Skip to main content
15,885,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I have a DataTable StudentsDtb having String DataType Column roll_no
roll_no holding data's like the following
C#
1
2
3
3a
3b
4
5
6
7
8
9
10
11
11a
12
13
13a
13b

From the above data I wish to have a max(roll_no) as 13. Is I possible?

object MyComputeValue=StudetsDtb.Compute(Max(roll_no),"");??????

Thanks

What I have tried:

Tried to find a Maximum Value from a String Column DataTable
Posted
Updated 18-Jun-20 2:51am

try this:

SQL
select max(case when isnumeric(roll_no)=0 then 0 else roll_no end) as max_roll


if there's a chance your data will not always have a simple numeric value (in other words:

1
2
3b

you probably want to try this

SQL
SELECT MAX(SUBSTRING(string, PATINDEX('%[0-9]%', roll_no), PATINDEX('%[0-9][^0-9]%', roll_no + 't') - PATINDEX('%[0-9]%', 
                    roll_no) + 1)) AS max_roll
 
Share this answer
 
v3
Comments
Paramu1973 17-Jun-20 11:25am    
Hi, how to use this select statement like any codes? thanks
#realJSOP 17-Jun-20 12:06pm    
I have no idea what you're asking
Maciej Los 18-Jun-20 8:54am    
5ed!
This is a bit clunk but should work:
SQL
SELECT MAX(
  CASE WHEN T.roll_no NOT LIKE '%[^0-9]%' THEN CAST(T.roll_no AS INT) ELSE NULL END
) 
FROM Table AS T  

This will look at each entry: if there are non-numeric characters in it, it will return null, otherwise, it will convert the string into an integer. MAX() will filter out the nulls, and return the maximum integer.

The only caveat is that if you have '14a' and '14b' without '14', then 13 will be returned as the max.
 
Share this answer
 
Comments
Maciej Los 18-Jun-20 8:54am    
5ed!
If you would like to get the highest number from c# code, check this out:
C#
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("roll_no", typeof(string)));

dt.Rows.Add("1");
dt.Rows.Add("2");
dt.Rows.Add("3");
dt.Rows.Add("3a");
dt.Rows.Add("3b");
dt.Rows.Add("4");
dt.Rows.Add("5");
dt.Rows.Add("6");
dt.Rows.Add("7");
dt.Rows.Add("8");
dt.Rows.Add("9");
dt.Rows.Add("10");
dt.Rows.Add("11");
dt.Rows.Add("11a");
dt.Rows.Add("12");
dt.Rows.Add("13");
dt.Rows.Add("13a");
dt.Rows.Add("13b");


int highestNumber = dt.AsEnumerable()
	.Max(x=> Convert.ToInt32(Regex.Split(x.Field<string>("roll_no"), @"[a-zA-z]")[0]));
//result: 13
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900