Custom sorting string array in C #

I have a string array or arraylist that is passed to my C # program. Here are some examples of what these lines contain:

"Spr 2009" "Sum 2006" "Autumn 2010" "Autumn 2007"

I want to sort this array by year and then by season. Is there a way to write a sort function to tell her about sorting by year and season. I know that it would be easier if they were separate, but I can not help what is given to me.

+3
source share
5 answers

, , Comparison<string>, Array.Sort:

public static int CompareStrings(string s1, string s2)
{
    // TODO: Comparison logic :)
}
...

string[] strings = { ... };
Array.Sort(strings, CompareStrings);

:

List<string> strings = ...;
strings.Sort(CompareStrings);
+8

, , LINQ:

string[] seasons = new[] { "Spr", "Sum", "Fall", "Winter" };

string[] args = new[] { "Spr 2009", "Sum 2006", "Fall 2010", "Fall 2007" };

var result = from arg in args
             let parts = arg.Split(' ')
             let year = int.Parse(parts[1])
             let season = Array.IndexOf(seasons, parts[0])
             orderby year ascending, season ascending
             select new { year, season };
+2

. -- . , . , . , , .

0
0
var strings = new string[] {"Spr 2009", "Sum 2006", "Fall 2010", "Fall 2007"};
var sorted = strings.OrderBy(s => 
{
    var parts = s.Split(' ');
    double result = double.Parse(parts[1]);
    switch(parts[0])
    {
        case "Spr":
            result += .25;
            break;
        case "Sum"
            result += .5;
            break;
        case "Fall":
            result += .75;
            break;
    }
    return result;
});

Array.Sort, , , ArrayLists.

0
source

Source: https://habr.com/ru/post/1757697/


All Articles