2

I have a collection of strings:

/a/b/111.txt
/a/b/c/222.txt
a/b/333.txt
a/b/c/d/444.txt

I want to this collection to be ordered like this:

/a/b/111.txt
a/b/333.txt
/a/b/c/222.txt
a/b/c/d/444.txt

So all a/b are grouped together, and so on.

Can this be done using linq? Or some other way?

2
  • Can't you just sort by Path.GetDirectoryName(inputStringPathHere)? Commented Aug 21, 2016 at 13:32
  • data.OrderBy(x => x.Split('/').Length)? Commented Aug 21, 2016 at 13:36

3 Answers 3

2

Given

var input = new []
{
    @"/a/b/111.txt",
    @"/a/b/c/222.txt",
    @"a/b/333.txt",
    @"a/b/c/d/444.txt",
};

you can "normalize" the strings by removing the leading / (if any) and use that as sorting key:

var output = input.OrderBy(s => s.TrimStart('/')).ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

You can achieve this by removing all slashes from the string being compared:

items.OrderBy(item => item.Replace("/", ""));

Comments

0

You can do this,

 List<string> values = new List<string>();
 values.Add("/ a /b/111.txt");
 values.Add("/ a / b / c / 222.txt");
 values.Add("a / b / 333.txt");
 values.Add("a / b / c / d / 444.txt");            
 var sortedList = values.OrderBy(p => p.Count(c => c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar));

Working .Net Fiddle

1 Comment

The problem with this solution is, eg, if you have a path like /p/q/222.txt at the beginning of your sequence, it can be ordered as one of the first elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.