Linq-to-Entities Dynamic sorting

前端 未结 5 646
无人共我
无人共我 2021-02-04 03:51

This is my query, how can I use string as orderby parameter?

string sortColumn=\"Title\";

var  items = (from ltem in ctxModel.Items
              where ltem.Ite         


        
5条回答
  •  一生所求
    2021-02-04 04:21

    Here's another alternative, the EntitySorter. Allows a bit what dynamic LINQ does with strings, but wraps the operation in a object, just like with the Query Object pattern. It allows both sorting by strings, and by type safe constructs. Here are some examples:

    // Ways of defining an entity sorter
    // 1. Using strings:
    IEntitySorter sorter = EntitySorter
        .OrderBy("Address.City")
        .ThenByDescending("Id");
    
    // 2. Defining a sorter with lambda's
    IEntitySorter sorter = EntitySorter
        .OrderByDescending(p => p.Name)
        .ThenBy(p => p.Id)
        .ThenByDescending(p => p.Address.City);
    
    // 3. Using a LINQ query
    IEntitySorter sorter =
        from person in EntitySorter.AsQueryable()
        orderby person.Name descending, person.Address.City
        select person;
    
    // And you can pass a sorter from your presentation layer
    // to your business layer, and you business layer may look
    // like this:
    static Person[] GetAllPersons(IEntitySorter sorter)
    {
        using (var db = ContextFactory.CreateContext())
        {
            IOrderedQueryable sortedList =
                sorter.Sort(db.Persons);
    
            return sortedList.ToArray();
        }
    }
    

    You can find the code here.

提交回复
热议问题