Reputation: 13467
Please consider this SQL script:
DECLARE @date DATE
SELECT @date = GETDATE();
DECLARE @tbl TABLE (F1 INT, F2 INT, F3 DATETIME, F4 NVARCHAR(50))
INSERT INTO @tbl(F1,F2,F3,F4)
VALUES(6,0,DATEADD(DAY, -8, @date),'1nima'),
(21, 78, DATEADD(DAY, -5, @date), '2nima'),
(58, 1, DATEADD(DAY, 10, @date), 'nima'),
(6, 56, DATEADD(DAY, 1, @date), 'nima'),
(0, 21, DATEADD(DAY, 0, @date), '3nima'),
(13, 78, DATEADD(DAY, -8, @date), '8nima'),
(8, 0, DATEADD(DAY, -8, @date), '9nima')
SELECT * FROM @tbl ORDER BY F3 DESC,F1 ASC
it returns this result and this is correct:
Now I want write that code using linq orders don't work properly:
var lst = new List<cls>();
lst.Add(new cls() { F1 = 6, F2 = 0, F3 = DateTime.Today.AddDays(-8), F4 = "1nima" });
lst.Add(new cls() { F1 = 21, F2 = 78, F3 = DateTime.Today.AddDays(-5), F4 = "2nima" });
lst.Add(new cls() { F1 = 58, F2 = 1, F3 = DateTime.Today.AddDays(10), F4 = "nima" });
lst.Add(new cls() { F1 = 6, F2 = 56, F3 = DateTime.Today.AddDays(1), F4 = "nima" });
lst.Add(new cls() { F1 = 0, F2 = 21, F3 = DateTime.Today.AddDays(0), F4 = "3nima" });
lst.Add(new cls() { F1 = 13, F2 = 78, F3 = DateTime.Today.AddDays(-8), F4 = "8nima" });
lst.Add(new cls() { F1 = 8, F2 = 0, F3 = DateTime.Today.AddDays(-8), F4 = "9nima" });
var orderlist = lst.OrderByDescending(o => o.F3).OrderBy(o => o.F1).ToList();
GridView1.DataSource = orderlist;
GridView1.DataBind();
it returns this result but this is wrong order:
Why this two result are not equal?
thanks
Upvotes: 0
Views: 72
Reputation: 180987
In your statement;
lst.OrderByDescending(o => o.F3).OrderBy(o => o.F1).ToList();
...the second OrderBy replaces the sort criteria of the IEnumerable completely (ie replaces OrderByDescending) instead of adding an extra criteria.
What you want is to add an extra secondary sort criteria which is done by ThenBy();
lst.OrderByDescending(o => o.F3).ThenBy(o => o.F1).ToList();
Upvotes: 2
Reputation: 728
Did you Try Then By?
var orderlist = lst.OrderByDescending(o => o.F3).ThenBy(o => o.F1).ToList();
Upvotes: 1