开发者

Creating OrderBy parameter dynamically [duplicate]

开发者 https://www.devze.com 2023-02-08 11:11 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Dynamic LINQ OrderBy Hi,
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Dynamic LINQ OrderBy

Hi, I have a IEnumerable of a data class. I want to sort this collection based on user selection. How can i write a generic function which will 开发者_如何学Pythontake the field name to be sorted & will return something line IEnumerable.OrderBy(f => f.fieldName)?


Take a look here: Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)


You can achieve this easily. let assume we have an object (class) called Item as:

public class Item
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Name2 { get; set; }
}

and this an example of a data collection

var items = new List<Item>
                {
                    new Item {Name = "Test 1", Description = "Description 1"},
                    new Item {Name = "Test 2", Description = "Description 2"}
                };

using the switch condition like

IOrderedEnumerable<Item> orderedItems;
switch (selection)
{
    case 1:
        orderedItems = items.OrderBy(i => i.Name);
        break;
    case 2:
        orderedItems = items.OrderBy(i => i.Description);
        break;
    default:
        orderedItems = items.OrderBy(i => i.Name2);
        break;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消