how to convert series of integers into ordinals in C#

Kwebena Acquah 306 Reputation points

i am having a texbox1 with series of integers i would like to know if their is any way i can apply the conversion of these integers into ordinals. below is what i have tried:

when my button convert is clicked with code:

private void btnconvert_Click(object sender, RoutedEventArgs e)
foreach (int num in txtresults.ToString())
string[] parts = txtresults.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
double[] numbers = parts.Select(p => double.Parse(p)).ToArray();
double maximum = numbers.Max();
int position = Array.IndexOf(numbers, maximum);
parts[position] = AddOrdinal(num);
txtresults.Text = string.Join(" ", parts);

this is my method of conversion

public static string AddOrdinal(int num)
if (num <= 0) return num.ToString();

    switch (num % 100)  
        case 11:  
        case 12:  
        case 13:  
            return num + "th";  

    switch (num % 10)  
        case 1:  
            return num + "st";  
        case 2:  
            return num + "nd";  
        case 3:  
            return num + "rd";  
            return num + "th";  


please TimonYang-MSFT your answer is absolutely close enough for me but please i have some question "can i be able to change does largest values that will be having th added to them to different values like

we have 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 19th. in your Result ;

NOW: here is my question and exact want (Can i be able to change the highest value to be 1st and the next largest value will be 2nd, 3rd and 4th continuously within this series wherever we have similar integers we will have similar position say 19th and 19th will have 1st, 1st because they are both the largest values. but the positioning will continue as 3rd for 18th; 4th for 17th ; 5th for 16th; 6th for 15th; 7th for 14th; 8th for 13th; 9th for 12th; 10th for 11th; 11th for 10th; and 12th for 10th; 13th for 8th; etc.

is just like having 13 student in a class who took an examination and had different scores in a subject like English, when we want to rank them or say give them their result we need to calculate their position in the subject examination in such a way that we will definitely end up having some one in the class with the last position 13th even when we have student with similar position. this is what i want my button1_click event to do

thank you sir (for your help) and more help

please one more help; i was trying to save these positions to there respective columns in the database so i tried the following code can you preview and see if i can be corrected of most error committed please

 private void btnsavegraderecord_Click(object sender, RoutedEventArgs e)  
            SqlCommand cmd = new SqlCommand ("INSERT INTO tbl_grade VALUES @ENGLIS, @MATH, @SCIENCE", conn);  
            if (txtresults.Text.Contains(','))  
                string[] arryval = txtresults.Text.Split(',');//split values with ‘,’    
                int j = arryval.Length;  
                int i = 0;  
                for (i = 0; i < j; i++)  
                    cmd.Parameters.AddWithValue("@ENGLISH", arryval[i]);  
                    cmd.Parameters.AddWithValue("@MATH", txtresults.Text);  


(i.e. trying to update the database table with the positions rather the scores again please can you help on that too)

can i be thought how to do it right please (thanks in advance) (am using c# in wpf)

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,197 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,531 Reputation points

    I try to point out a few pieces of code that I found inappropriate.

    foreach (int num in txtresults.ToString())  

    textbox.ToString() will get this result:


    A string composed of Type and Text property, and you are converting it to int in the foreach loop, so it will be the value corresponding to the current letter in the ASCII table, for example, the first letter S corresponds to 83. I believe this is not you want.

    double[] numbers = parts.Select(p => double.Parse(p)).ToArray();  

    Linq is generally used for filtering and query work, try not to use it for modifying data.

    Although it does not produce exceptions, it does not conform to general coding standards and may confuse people at some point. It is better to use general loops.

    double[] numbers = parts.Select(p => double.Parse(p)).ToArray();  
    double maximum = numbers.Max();  
    int position = Array.IndexOf(numbers, maximum);  

    I don't understand why we need to find the position, using parts[position] will always only add th after the largest number, no matter how many times it loops.
    I made some changes to the code, the current code is as follows:

                   private void button1_Click(object sender, EventArgs e)  
            string[] parts = textBox1.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);  
            double[] numbers = new double[parts.Length];  
            for (int i = 0; i < parts.Length; i++)  
                numbers[i] = double.Parse(parts[i]);  
            double[] sortedNums = numbers.OrderByDescending(n => n).ToArray();  
            int[] positions = new int[numbers.Length];  
            for (int i = 0; i < positions.Length; i++)  
                positions[i] = Array.IndexOf(sortedNums, numbers[i])+1;  
            for (int i = 0; i < numbers.Length; i++)  
                parts[i] = AddOrdinal(positions[i]);  
            textBox1.Text += Environment.NewLine;  
            textBox1.Text += string.Join(" ", parts);  
             DataTable dataTable=  ToDataTable(parts, numbers);  
       public static void InsertIntoDataBase (DataTable dataTable)  
            string connString = @"your connection string";  
            using (SqlConnection sqlConnection = new SqlConnection(connString))  
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection))  
                    sqlBulkCopy.DestinationTableName =  
        public static DataTable ToDataTable(string[] ranks,double[] scores)  
            DataTable dataTable = new DataTable();  
            dataTable.Columns.Add("ID", typeof(int));  
            dataTable.Columns.Add("score", typeof(double));  
            dataTable.Columns.Add("rank", typeof(string));  
            for (int i = 0; i < ranks.Length; i++)  
                dataTable.Rows.Add(i + 1, scores[i], ranks[i]);  
            return dataTable;  


    Is this what you need?

    If not, please describe what the final result you need is.


    To create a new table as an example.

    First, create a new table in the database.

    CREATE TABLE [dbo].[rangkingTable]  
        [score] FLOAT NULL,   
        [rank] NCHAR(10) NULL  

    Then refer to the two new methods I added in the code above.

    Take the rankingTable I created yesterday as an example, suppose it looks like this now:
    We can update it in batches through SqlDataAdapter, like this:

            public static void UpdateTable(string[] ranks)  
                string connString = @"your conn string";  
                using (SqlConnection connection = new SqlConnection(connString))  
                    SqlDataAdapter dataAdpater = new SqlDataAdapter(  
            "select * from rankingTable",  
                    dataAdpater.UpdateCommand = new SqlCommand(  
                    "UPDATE rankingTable SET rank = @rank " +  
                    "WHERE id = @id", connection);  
                       "@rank", SqlDbType.NVarChar, 15, "rank");  
                    SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(  
                      "@id", SqlDbType.Int);  
                    parameter.SourceColumn = "id";  
                    parameter.SourceVersion = DataRowVersion.Original;  
                    DataTable dataTable = new DataTable();  
                    for (int i = 0; i < dataTable.Rows.Count; i++)  
                        dataTable.Rows[i]["rank"] = ranks[i];  

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful