Sort lines by position of another line
What is the best way - Given string A and rowset C, order the strings in the collection in non-decreasing order of position A in the strings.
For example,
A= abc C= [deabc, abc, dabc, dad] Sorted C= [abc, dabc, deabc]
My idea is to loop over the collection and put it in a HashMap / Dictionary with the position A in C [i] as the index. And then let's build a sorted collection from the HashMap. This is not a homework problem. Just wanted to know an efficient way / algorithm to do this. Any pointers would be helpful.
source to share
Here's a simple way with LINQ:
var SortedC = C.OrderBy (d => d.IndexOf(A)).ToArray();
Note that rows not containing A will be sorted at the beginning because it IndexOf
returns -1
. Also, the behavior for rows with A at the same index is undefined and will be returned in no particular order unless you provide a sort .ThenBy
to handle them.
source to share