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:
You can also delete the
SortByStringPosmethod and callArray.Sort(arr, new MyStrComparer("-", ascending));from anywhere in your code.