1

I've got a collection of that type:

IEnumerable<FileInfo> files;

I'm trying to sort the files so that all files with the name 'index.js' will appear at the beginning of the list. I don't mind how the rest of the files are sorted.

What would be the LINQ query for that ?

Sam
  • 13,934
  • 26
  • 108
  • 194

3 Answers3

12

Method syntax

files = files.OrderBy(x => x.Name == "index.js" ? 0 : 1);

Query syntax

files = from x in files
        orderby x.Name == "index.js" ? 0 : 1
        select x;
Aducci
  • 26,101
  • 8
  • 63
  • 67
  • 1
    @DanielHilgarth - Thank you, I cleaned it up – Aducci Apr 23 '13 at 19:02
  • You could acually files.OrderByDescending(x => x.Name.ToLower() == "index.js"); – Andreas Johansson Apr 23 '13 at 19:05
  • OrderBy perfectly works with boolean keys, so it's no need to use ternary operator ;) – tukaef Apr 23 '13 at 19:05
  • @2kay, i beat you to it :) – Andreas Johansson Apr 23 '13 at 19:06
  • 1
    @AndreasJohansson It *works* but it's much less readable. It's not intuitive that `true > false` and even if this code compiles, it's not clear to the reader whether the matching values should be at the start or at the end, so the added conditional operator is well worth the few additional characters. – Servy Apr 23 '13 at 19:08
  • 1
    that's great ! At first I was doing it with a custom IComparer, but this is so much neater :) – Sam Apr 24 '13 at 06:26
2

Try like this;

var f = files.OrderBy(x => "index.js".Equals(x.Name) ? 0 : 1);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Here's one "clever" way:

IEnumerable<FileInfo> ordered = files.OrderBy(x => "index.js".Equals(x.Name) ? 0 : 1);
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280