在LINQ中重新排序记录

时间:2014-11-24 07:45:38

标签: c# linq entity-framework asp.net-mvc-4

我有一个像

这样的实体
public class StateInformation
{
    public string id { get; set; }
    public bool ?locked { get; set; }
    public bool ?hidden { get; set; }
}

在某些情况下,隐藏字段的值为 true ,如

{
"columns": [
    {
        "id": "prescribingClNDC"
    },
    {
        "id": "prescribingClNDCDes",
        "locked": false
    },
    {
        "id": "prescribindClGenericName",
        "hidden": true,
        "locked": false
    },
    {
        "id": "prescribingClTheraputic",
        "locked": false,
        "width": 100
    },
    {
        "id": "prescribingClTotalCost",
        "locked": false,
        "width": 100,
        "hidden": true
    }
]

}

这种情况我需要重新排序所有记录。也就是说,如果记录具有隐藏字段值'true'将放在记录集的末尾,如

{
"columns": [
    {
        "id": "prescribingClNDC"
    },
    {
        "id": "prescribingClNDCDes",
        "locked": false
    },
    {
        "id": "prescribingClTheraputic",
        "locked": false,
        "width": 100
    },
    {
        "id": "prescribingClTotalCost",
        "locked": false,
        "width": 100,
        "hidden": true
    },
    {
        "id": "prescribindClGenericName",
        "hidden": true,
        "locked": false
    }
]

}

linq中是否有任何直接的方法来处理这个问题?

由于 预先

1 个答案:

答案 0 :(得分:3)

尝试:

var info = new List<StateInformation>() {
    new StateInformation() { id="1", locked = false, hidden = true },
    new StateInformation() { id="2", locked = false, hidden = false },
    new StateInformation() { id="3", locked = false}
};

var results = info.OrderBy(x => x.hidden.HasValue && x.hidden.Value).ToList();

输出将是:

2 False null 
3 False False 
1 False True