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.

+3


source to share


2 answers


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.

+4


source


stringsArray.OrderBy(s => s.IndexOf("a"))

      



+1


source







All Articles