C#LINQ命令错误?

时间:2015-06-12 12:41:06

标签: c# linq

我有一个我想订购的对象列表,但我无法弄清楚如何使用LINQ来做,也许我认为LINQ以不同的方式工作。

我可以通过使用示例中的where子句来解决问题,但我想了解发生了什么。

任何人都可以向我解释为什么我无法在"值中获得预期的结果"变量?

由于

预期结果

[列表中对象的顺序"值"]:

new MyClass{Ordinal = 1, A = true, B = Status.Released, C = 3}
new MyClass{Ordinal = 0, A = true, B = Status.Released, C = 2}
new MyClass{Ordinal = 4, A = true, B = Status.Skipped, C = 5}
new MyClass{Ordinal = 2, A = true, B = Status.Skipped, C = 4}
new MyClass{Ordinal = 3, A = false, B = Status.Skipped, C = 1}

样品

public class Program
{
    static void Main(string[] args)
    {
        var lst = new List<MyClass>{ 
            new MyClass{Ordinal = 0, A = true, B = Status.Released, C = 2},
            new MyClass{Ordinal = 1, A = true, B = Status.Released, C = 3},
            new MyClass{Ordinal = 2, A = true, B = Status.Skipped, C = 4},
            new MyClass{Ordinal = 3, A = false, B = Status.Skipped, C = 1},
            new MyClass{Ordinal = 4, A = true, B = Status.Skipped, C = 5}
        };


        var workaround = lst.Where(i => i.B != Status.Skipped && i.B != Status.Cancelled)
            .OrderByDescending(i => i.A)
            .ThenByDescending(i => i.C)
            .ToList();

        var values = lst.OrderByDescending(i => i.A)
            .ThenBy(i => i.B == Status.Skipped && i.B == Status.Cancelled)
            .ThenByDescending(i => i.C)
            .ToList();

        /* order of the objects in "values"
            new MyClass{Ordinal = 4, A = true, B = Status.Skipped, C = 5}
            new MyClass{Ordinal = 2, A = true, B = Status.Skipped, C = 4}
            new MyClass{Ordinal = 1, A = true, B = Status.Released, C = 3}
            new MyClass{Ordinal = 0, A = true, B = Status.Released, C = 2}
            new MyClass{Ordinal = 3, A = false, B = Status.Skipped, C = 1}
        */
    }
}

public class MyClass
{
    public int Ordinal { get; set; }

    public bool A { get; set; }
    public Status B { get; set; }
    public int C { get; set; }
}

public enum Status
{
    Unknown,
    Released,
    Cancelled,
    Received,
    Processing,
    Succeeded,
    Failed,
    Skipped
}

1 个答案:

答案 0 :(得分:5)

lambda表达式

Sub Test()
    On Error GoTo err_handler
    Dim wb As Workbook
    Dim fname As String
    Dim tempname As String
    fname = "C:\Programs\testbook.xlsx"
    Set wb = Workbooks.Add
    wb.Sheets(1).Range("A1").Value = Now 'for testing purposes
    wb.SaveAs fname
    Exit Sub
err_handler:
    tempname = "C:\Programs\name_i_will_never_use.xlsx"
    wb.SaveAs tempname
    wb.Close
    Kill tempname
End Sub
用于i => i.B == Status.Skipped && i.B == Status.Cancelled 函数的

ThenBy的每个实例映射到MyClass,假设falseStatus.Skipped是不同的值;这导致没有有用的排序。也许你的意思是

Status.Cancelled

订购状态为i => i.B != Status.Skipped && i.B != Status.Cancelled Status.Skipped的条目到底部。