Reputation: 449
i working on c# project(winform).
on my project, i sorted a datatable like this:
dt.DefaultView.Sort = "a ASC, b ASC, c ASC";
now with below expression, i sorted a generic list, but results is different against datatale results.
var newList = oldList.OrderBy(x => x.a).OrderBy(x => x.b).OrderBy(x => x.c).ToList();
how can sorted my generic list like datatable results? (i want have same sort datatable results in generic list)
thanks.
Upvotes: 0
Views: 317
Reputation: 236268
Use ThenBy
/ThenByDescending
after first OrderBy
/OrderByDescending
operator - it performs subsequent ordering of already ordered sequence:
var newList = oldList.OrderBy(x => x.a)
.ThenBy(x => x.b)
.ThenBy(x => x.c)
.ToList();
Otherwise you are re-ordering full sequence each time by different value (i.e. you are introducing new primary ordering that ignores previous ordering - see Remarks section on MSDN). And you'll end up with sequence sorted only by value provided to last OrderBy
call (property c
in your case). Your current code is equivalent of
dt.DefaultView.Sort = "a ASC";
dt.DefaultView.Sort = "b ASC";
dt.DefaultView.Sort = "c ASC";
Upvotes: 6