Isha John
Isha John

Reputation: 623

Re-order records in LINQ

I have a an entity set like

public class StateInformation
{
    public string id { get; set; }
    public bool ?locked { get; set; }
    public bool ?hidden { get; set; }
}

In some situation hidden field has the value true like

{
"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
    }
]

}

This case i need to reorder all the records. That is, if a record have hidden field value 'true' will place at the end of the record set like

{
"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
    }
]

}

Is there any direct methode available in linq to handle this..?

Thanks Advance

Upvotes: 2

Views: 85

Answers (1)

Marian Ban
Marian Ban

Reputation: 8168

try:

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

the output will be:

2 False null 
3 False False 
1 False True 

Upvotes: 3

Related Questions