# how to convert series of integers into ordinals in C#

306 Reputation points
2021-03-02T23:05:08.35+00:00

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);
txtresults.Text = string.Join(" ", parts);
}
}

this is my method of conversion

{
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";
default:
return num + "th";
}
}
``````

Update:

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

UPDATE
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);
con.Open();

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.Clear();
cmd.ExecuteNonQuery();

cm.ExecuteNonQuery();
}
``````

(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)

C#
C#
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.
10,688 questions

1. 9,586 Reputation points
2021-03-03T02:26:00.697+00:00

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++)
{
}
textBox1.Text += Environment.NewLine;
textBox1.Text += string.Join(" ", parts);

DataTable dataTable=  ToDataTable(parts, numbers);
InsertIntoDataBase(dataTable);
}
public static void InsertIntoDataBase (DataTable dataTable)
{
string connString = @"your connection string";
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection))
{
sqlBulkCopy.DestinationTableName =
"dbo.rangkingTable";
sqlBulkCopy.WriteToServer(dataTable);
}
}
}
public static DataTable ToDataTable(string[] ranks,double[] scores)
{
DataTable dataTable = new DataTable();
for (int i = 0; i < ranks.Length; i++)
{
}
return dataTable;
}
``````

Result:

Is this what you need?

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

Update（2021.3.10）：

To create a new table as an example.

First, create a new table in the database.

``````CREATE TABLE [dbo].[rangkingTable]
(
[Id] INT NOT NULL PRIMARY KEY,
[score] FLOAT NULL,
[rank] NCHAR(10) NULL
)
``````

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

Update（2021.3.11）：
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))
{
connection.Open();

"select * from rankingTable",
connection);

"UPDATE rankingTable SET rank = @rank " +
"WHERE id = @id", connection);

"@rank", SqlDbType.NVarChar, 15, "rank");

"@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];
}