0

Hello I'm not clear why my linq statement orderby is not working as expected.

  var q = from DirectoryInfo subDirectory
          in item.GetDirectories()
          orderby (item.Name == "TableDefinition" ? 1 : 2), item.Name
          select subDirectory;
  foreach (DirectoryInfo subDirectory in q)
  {
    Execute(subDirectory);
  }

I want the items sorted first by seeing if the name is "TableDefinition" or not, then secondly just by name.

It appears that it's just sorting by name only, in alpha order ascending.

Rob
  • 25,569
  • 15
  • 73
  • 87
toddmo
  • 16,852
  • 9
  • 86
  • 91
  • See http://stackoverflow.com/questions/298725/multiple-order-by-in-linq . This may be the solution. – GEEF Feb 03 '16 at 21:23
  • you need custom IComparer here i guess – Ehsan Sajjad Feb 03 '16 at 21:23
  • @hvd, yes, the subdirectory is exactly named "TableDefinition" – toddmo Feb 03 '16 at 21:26
  • @hvd Correct you are. As a debugging attempt I might try the first part of the query (from x in y), cache it, then execute the LINQ style of Orderby(...).ThenBy(...). It *shouldn't* change the outcome, but I would be tempted to try it anyway. – GEEF Feb 03 '16 at 21:28

1 Answers1

3

You have to use subDirectory in place of item

var q = from DirectoryInfo subDirectory
        in item.GetDirectories()
        orderby (subDirectory.Name == "TableDefinition" ? 1 : 2), subDirectory.Name
        select subDirectory;
foreach (DirectoryInfo subDirectory in q)
{
    Execute(subDirectory);
}
Ulugbek Umirov
  • 12,231
  • 2
  • 20
  • 29