1

Is there a way of changing what property a Linq statement does a Where and an OrderBy please?

I have the following example function that I am trying to make more flexible:

public static List<SADatastore.SA_Items> BuildResourcesModel2(
        int Take = 10000,
        int Skip = 0,
        string filterBy = null,
        string filterString = null,
        string sortBy = "ItemID",
        string sortOrder = "asc"
        ) {

        List<SADatastore.SA_Items> theAnswer = new List<SA_Items>();

        using (SADatastoreEntities db = new SADatastoreEntities(Properties.Settings.Default.ConnectionString)) {
            theAnswer = db.SA_Items
                        .Where(x => x.SA_Categories.Description.ToLower().Contains(filterString.ToLower()))
                        .OrderBy(x=>x.ItemID)
                        .Take(Take)
                        .Skip(Skip)
                        .ToList();
        }

        return theAnswer;
    }

As you can see, as it's written at the moment, it is always doing the where based on the Category Description and Ordering Ascending based on ItemID

Is there a way to rewrite this in a dynamic way so if it's called with the parameters

filterBy = "Manufacturer"
filterString "Ford"
sortBy = "Manufacturer"
sortOder = "Desc"

It would dynamically change the Where and Order clauses?

Any help would be greatly appreciated!

Trevor Daniel
  • 3,470
  • 10
  • 42
  • 79
  • Did you see this SO post http://stackoverflow.com/questions/1299534/linq-passing-lambda-expression-as-parameter-to-be-executed-and-returned-by-meth ? – PMerlet Jan 06 '17 at 14:41
  • There are a lot of similar questions on SO (separately for filtering and sorting), as well as solutions - starting with Dynamic LINQ package thru building expressions dynamically with `System.Linq.Expressions.Expression` class methods. – Ivan Stoev Jan 06 '17 at 14:43
  • 1
    https://blog.cincura.net/229310-sorting-in-iqueryable-using-string-as-column-name/ – Darin Dimitrov Jan 06 '17 at 14:44

2 Answers2

-1

You should be able to do this by using Reflection.

x.SA_Categories.GetType().GetProperty(filterby).GetValue(x);  //this gets you the value of the property you're filtering by.  

A similar situation is posted here.

Community
  • 1
  • 1
CDove
  • 1,836
  • 9
  • 17
-2

Break up your linq query:

var items = db.Items.Where(x => x.CategoryName == "Category A");

if (sortOrder == "desc") items = items.OrderByDesc(x => x.Id);
else items = items.OrderBy(x => x.Id);

return items.ToList();
benjrb
  • 557
  • 3
  • 13