Mert
Mert

Reputation: 6572

group by name order

There are two types "files" and "folders" I want to group by files and folders but folders must be on top. how can I do this in LINQ?

public class DocumentItem
{
    public string Type { get; set; }
    public string Name { get; set; }
}

List<DocumentItem> result = SPHelper.GetList().OrderBy(x => x.Type).ToList();

Upvotes: 2

Views: 92

Answers (3)

Ferit Buyukkececi
Ferit Buyukkececi

Reputation: 2685

OrderByDescending will do the trick in this specific case, as follows:

List<DocumentItem> result = SPHelper.GetList().OrderByDescending(x => x.Type).ToList();

If you need also need to sort within each group, say alphabetically, then you can append this query with ThenBy:

List<DocumentItem> result = SPHelper.GetList().OrderByDescending(x => x.Type)
                            .ThenBy(x => x.Name).ToList();

One last option can be sorting by boolean condition, as follows:

List<DocumentItem> result = SPHelper.GetList()
                            .OrderByDescending(x => x.Type == "Folder").ToList();

Here, OrderByDescending sorts from True to False, thus groups your entities.

Upvotes: 0

Kamolas81
Kamolas81

Reputation: 549

Either add a property to DocumentItem to represent that higher priority or treat them as separate groups and in the end add both, in order, to a final collection.

Upvotes: 0

VMAtm
VMAtm

Reputation: 28345

You can use OrderByDescending method to get the reverse sort by Type:

var result = SPHelper.GetList().OrderByDescending(x => x.Type).ToList();

Can't say why do you need grouping by type in your example.

Upvotes: 2

Related Questions