2

I have a table that I want to pull items by name in a certain order and by date.

id name  date
1  XYZ   1:30
2  ABC   1:40
3  LMNOQ  1:50
4  ABC   1:20

I created the order

List<string> itemNames = new List<string>();
       documentOrder.Add("XYZ");
       documentOrder.Add("ABC");     
       documentOrder.Add("LMNOQ");

Then pulled the data, I think order will stay intact.

var myTable = _context.TheTable.Where(x => itemNames.Contains(x.id));

myTable data will look like

id name  date
1  XYZ   1:30
2  ABC   1:40
4  ABC   1:20
3  LMNOQ  1:50

Now I need to sort by dates without messing up the name order. I need it look like this.

id name  date
1  XYZ   1:30
2  ABC   1:20
4  ABC   1:40
3  LMNOQ  1:50
user1854438
  • 1,784
  • 6
  • 24
  • 30
  • Possible duplicate of [C# List<> Sort by x then y](https://stackoverflow.com/questions/289010/c-sharp-list-sort-by-x-then-y) – Jota.Toledo Nov 01 '17 at 20:03
  • Is what you try to achieve [a stable sort on Date column](https://stackoverflow.com/a/13710006/7034621)? – orhtej2 Nov 01 '17 at 20:26

2 Answers2

3
var myTable = _context.TheTable.Where(x => itemNames.Contains(x.id))
                      .OrderBy(x => x.name).ThenBy(x => x.date);
Sparrow
  • 2,548
  • 1
  • 24
  • 28
2

When using an IQueryable you can get it ordered as you want (by name, then by date... which looks a bit like a time) with multiple ordering statements.

var orderedQueryable = queryable.OrderBy(q => q.Name).ThenBy(q => q.Date);
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • If I OrderBy Name, won't that order the name Alphabetically? – user1854438 Nov 01 '17 at 20:03
  • @user1854438 yes it will. Your question shows them alphabetically... did you want something different? – Fenton Nov 01 '17 at 20:07
  • Yeah, sorry my example was a mistake. I'll update the question – user1854438 Nov 01 '17 at 20:14
  • To simply "preserve the original name order", you'll need to populate an additional property, so you can still order. For example, if you iterate the collection and assign an order integer to each row, and increment it each time the name changes, you could order by "OriginalOrder" then by "Date". – Fenton Nov 01 '17 at 20:18