luckymow8
luckymow8

Reputation: 72

How to sort collection of file paths using c# linq

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?

Upvotes: 2

Views: 529

Answers (3)

Ivan Stoev
Ivan Stoev

Reputation: 205599

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();

Upvotes: 2

Aleksey L.
Aleksey L.

Reputation: 37928

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

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

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

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

Upvotes: 0

Related Questions