mardi 18 février 2020

How to sort a List of strings by multiple conditions

I have a List of strings that looks like this (completely unsorted):

[Title b] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title a] \t [text] \t complete
[Title c] \t [text] \t complete
...

It shall be sorted to look like either this:

[Title a] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title b] \t [text] \t complete
[Title c] \t [text] \t complete
...

Or this (which way it shall be sorted is selectable)

[Title a] \t [text] \t complete
[Title j] \t [text] \t complete
[Title s] \t [text] \t complete
...

[Title b] \t [text] \t incomplete
...

My approach on this whole sorting thing is kinda dirty and not sleek at all and also only solves the second way of sorting.

List<string> sortedTps = new List<string>();
List<string> completeTps = new List<string>();
List<string> incompleteTps = new List<string>();
List<string> errorTps = new List<string>();

foreach (string tp in tpByProduct)
{
    if (tp.Contains("\t complete"))
    {
        completeTps.Add(tp);
    }
    else if (tp.Contains("\t incomplete"))
    {
        incompleteTps.Add(tp);
    }
 }

 completeTps.Sort();
 incompleteTps.Sort();

 foreach(string tp in completeTps)
 {
    sortedTps.Add(tp);
 }

 foreach(string tp in incompleteTps)
 {
    sortedTps.Add(tp);
 }

Hope you guys can show me how to do this better and shorter ^^

Aucun commentaire:

Enregistrer un commentaire