How to Check for bigest Numeric Value in a Text Box with many Values

KwebenaAcquah-9104 306 Reputation points
2021-01-23T05:30:26.767+00:00

i have a text box with many numeric values from deferent columns in a data grid i would like to check from the highest numeric value `in the textbox to the least and change these specific values to "1", "2" or "H1", "H2" etc. until each value is replaced with there ranking from highest to lowest value and save each back to the data grid according to their columns is it possible ? and can some one help me out please.
59723-mywork.png

Help !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! please help !!!!!!!!!!!!!!!!!!!!!! am stalked please help !

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.
11,113 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,456 Reputation points
    2021-01-23T12:17:17.273+00:00

    Hello @KwebenaAcquah-9104

    The following places results into a ListBox for testing only, you would assign these values back to your DataGridView.

    DO NOT

    Get hung up on the ListBox, it's used simply to validate the code presented works.

    Full source

    https://github.com/karenpayneoregon/csharp-features/tree/master/ParsingArray

    All code has been done in VS2019

    59700-11111111111.png

    A language extension is used (to keep code in the form clean and is reusable) to split the text into a string array. Create a class named ControlExtensions and replace the default content with this.

    Class

    using System;  
    using System.Windows.Forms;  
    
    namespace ParsingArray.Extensions  
    {  
        public static class ControlExtensions  
        {  
            public static string[] ToStringArray(this TextBox textBox, char separator = ' ') =>   
                textBox.Text.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);  
        }  
    }  
    

    Next create a class named Extensions and place the code below in.

    • AllDecimals returns true if all elements in the string array can be converted to decimal (is optional as ToDecimalArray below will handle issues)
    • ToDecimalArray converts a string array to decimal, if AllDecimals is not used and an element can not be converted it's value will be 0.
    • ItemsFromArray creates a temp container which is used by MaxItem to get the max value

      Class

      namespace ParsingArray.Extensions
      {
      public static class Extensions
      {
          public static decimal[] ToDecimalArray(this string[] sender)  
          {  
      
              var decimalArray = Array.ConvertAll(sender, (input) =>  
              {  
                  decimal.TryParse(input, out var decimalValue);  
                  return decimalValue;  
              });  
      
              return decimalArray;  
      
          }  
      
          public static List<Item> ItemsFromArray(this decimal[] sender) =>   
              sender.Select((value, Index) => new Item() {Index = Index, Value = value}).ToList();  
      
          public static bool AllDecimals(this string[] sender) =>   
              sender.All(item => decimal.TryParse(item, out var test));  
      
          public static Item MaxItem(this List<Item> sender) =>   
              sender.OrderByDescending(x => x.Value).FirstOrDefault();  
      }  
      
      }

    Form code

    namespace ParsingArray  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
    
            private void button1_Click(object sender, EventArgs e)  
            {  
    
                listBox1.Items.Clear();  
    
                var stringValues = textBox1.ToStringArray();  
    
                if (!stringValues.AllDecimals()) return;  
                var result = stringValues.ToDecimalArray().ItemsFromArray().MaxItem();  
                if (result != null) stringValues[result.Index] = "H";  
    
                listBox1.Items.AddRange(stringValues);  
    
            }  
        }  
    }  
    

    Update

    This will rank each item from max to lowest.

    private void button2_Click(object sender, EventArgs e)  
    {  
        var stringValues = textBox1.ToStringArray();  
    
        var itemList = stringValues  
            .ToDecimalArray()  
            .ItemsFromArray()  
            .OrderByDescending(item => item.Value)  
            .ToList();  
    
        for (int index = itemList.Count - 1; index >= 0; --index)  
        {  
            itemList[index].Text = $"H{index + 1}";  
        }  
    
        foreach (var item in itemList)  
        {  
            Debug.WriteLine($"{item.Text}\t{item.Value}");  
        }  
    }  
    

    Output

    H1  1126.90  
    H2  909.50  
    H3  467.20  
    H4  400.20  
    H5  397.50  
    H6  387.60  
    H7  371.50  
    H8  366.10  
    H9  356.90  
    H10 345.60  
    H11 335.00  
    H12 289.40  
    H13 283.40  
    H14 87.00  
    H15 77.00  
    H16 76.00  
    H17 76.00  
    H18 54.00  
    H19 45.00  
    H20 34.00  
    H21 23.00  
    H22 8.00  
    H23 4.00  
    H24 4.00  
    H25 3.00  
    H26 3.00  
    
    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Alberto Poblacion 1,561 Reputation points
    2021-01-23T10:21:18.437+00:00

    First, split the text into its contained values. Then convert them to numeric. Then calculate the max. Then you can concatenate them back if you wish, after changing the one that you found:

    string[] parts = textBox1.Text.Split(new char[]{' '}, StringSplitOptions.IgnoreEmptyEntries);
    double[] numbers = parts.Select(p => double.Parse(p)).ToArray();
    double maximum = numbers.Max();
    int position = Array.IndexOf(numbers, maximum);
    parts[position] = "H";
    textBox1.Text = string.Join(" ", parts);
    

    Of course, this allows plenty of refinements, such as using a TryParse instead of double.Parse to avoid errors if one of the elements does not have the right format, or using a loop to find the index at the same time as the maximum, etc.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.