I would like to know how can i sort items of a string[] according to a specific string position. For instance i want to sort the following array by the substring " - "
Input: {xx - c, xxxxx - b, yyy - a, mlllll - d}
Expected output: {yyy - a, xxxxx - b, xx - c, mlllll - d}
What i have so far is the following:
public string[] SortByStringPos(string[] arr, string str, bool ascending)
{
if (ascending)
{
var result = from s in arr
where s.Length >= s.IndexOf(str)
orderby s[s.IndexOf(str)] ascending
select s;
return result.ToArray();
}
else
{
var result = from s in arr
where s.Length >= s.IndexOf(str)
orderby s[s.IndexOf(str)] descending
select s;
return result.ToArray();
}
}
Can someone drop me a hint...?
For a better performance and design, I recommend you use:
public void SortByStringPos(string[] arr, string str, bool ascending)
{
Array.Sort(arr, new MyStrComparer("-", ascending));
}
class MyStrComparer : Comparer<string>
{
string delimiter;
bool isAscending;
public MyStrComparer(string aStr, bool ascending)
{
delimiter = aStr;
isAscending = ascending;
}
public override int Compare(string x, string y)
{
var r = GetMySubstring(x).CompareTo(GetMySubstring(y));
return isAscending ? r : -r;
}
string GetMySubstring(string str)
{
return str.IndexOf(delimiter) != -1 ? str.Substring(str.LastIndexOf(delimiter)) : string.Empty;
}
}
You can also delete the SortByStringPos
method and call Array.Sort(arr, new MyStrComparer("-", ascending));
from anywhere in your code.
orderby x=>x.Substring(x.LastIndexOf('-'))
i guess
so you need to order it in usual manner, then you can use this, like orderBy .... thenBy
static void Main()
{
var input = new[] { "xx - c", "xx - b", "yy - a", "ml - d", };
var delimeter = "-";
var isAscending = true;
var res = Sort(input, delimeter, isAscending);
}
static string[] Sort(string[] input, string delimeter, bool isAscending)
{
var withDelimeter = input.Where(p => p.Contains(delimeter));
var withoutDelimeter = input.Except(withDelimeter);
Func<string, string> selector = p => p.Substring(p.IndexOf(delimeter));
return
(
isAscending
? withDelimeter.OrderBy(selector)
.Concat(withoutDelimeter.OrderBy(p => p))
: withoutDelimeter.OrderByDescending(p => p)
.Concat(withDelimeter.OrderByDescending(selector))
)
.ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With