0

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 take the field name to be sorted & will return something line IEnumerable.OrderBy(f => f.fieldName)?

Community
  • 1
  • 1
Rik
  • 21
  • 2
  • 5

2 Answers2

2

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

Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
0

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;
}
Ahmed Magdy
  • 5,956
  • 8
  • 43
  • 75