简体   繁体   中英

Sorted array using nested loops and substring method (C#)

I am trying to manually sort an array using string inputs that end with a number which I want to sort from highest to lowest.

For example I can start with this output: ,Name1: 1540,Name2: 2660,Name3: 80,Name4: 380

And in the end it should look like this: ,Name2: 2660,Name1: 1540,Name4: 380,Name3: 80

private string[] OrderHighToLow(string[] data)
    {
        string temp;
        for (int i = 0; i < data.Length; i++)
        {
            for (int y = 0; y < i; y++)
            {
                if (int.Parse(data[y].Substring((data[y].IndexOf(':') + 2))) > int.Parse(data[i].Substring((data[i].IndexOf(':') + 2)))) 
                {
                    temp = data[i];
                    data[i] = data[y];
                    data[y] = temp;
                }
            }
        }
        return data;
    }

This is what I have tested. According to me, this should work, but the point is it doesn't, the application just crashes. So, if anyone here can figure out why that may be, I would be very thankful. Thanks in advance.

your comparison is worng

int.Parse(data[y].Substring((data[y].IndexOf(':') + 2)))

less than Not greater than

 if (int.Parse(data[y].Substring((data[y].IndexOf(':') + 2))) < int.Parse(data[i].Substring((data[i].IndexOf(':') + 2)))) 

This should do the job with the Help of System.Linq :

private string[] OrderHighToLow(string[] data)
{
    //create a temporary dictionary, which makes sorting easier
    var tmpMap = new Dictionary<string, int>();
    foreach (var item in data)
    {
        //split the string 
        var elems = item.Split(":");
        //add string and int pair to the dictionary
        tmpMap.Add(elems[0], int.Parse(elems[1]));
    }

    //sort Dictionary by value and use select to rebuild the string, then convert it back to an array
    return tmpMap.OrderByDescending(x => x.Value).Select(x => $"{x.Key}: {x.Value}").ToArray();
}

Hope this helps.

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