OrderByDescending(o => o.X).OrderBy(o => o.Y)无法正常工作

时间:2014-07-13 04:58:56

标签: c# linq c#-4.0 linq-to-sql linq-to-entities

请考虑这个SQL脚本:

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

它返回此结果,这是正确的:

enter image description here

现在我想写一下使用linq命令的代码不能正常工作:

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();

它会返回此结果,但这是错误的顺序:

enter image description here

为什么这两个结果不相等?

感谢

2 个答案:

答案 0 :(得分:2)

在你的陈述中;

lst.OrderByDescending(o => o.F3).OrderBy(o => o.F1).ToList();

...第二个OrderBy完全替换IEnumerable的排序标准(即替换OrderByDescending),而不是添加额外的标准。
您想要的是添加一个额外的二级排序标准,由ThenBy();

完成
lst.OrderByDescending(o => o.F3).ThenBy(o => o.F1).ToList();

答案 1 :(得分:1)

你试过吗?

var orderlist = lst.OrderByDescending(o => o.F3).ThenBy(o => o.F1).ToList();