Domanda

I am using a common function for filtering a list of records.

the function is below:

  class FilterRecords
{

    public static object ParseExpression(string Condition, string FilterColumn)
    {
        string _operator = "";
        string _condition = "";                       

        if (Condition.Substring(0, 1) == "<" || Condition.Substring(0, 1) == ">")
        {
            _operator = Condition.Substring(0, 1);

            if (Condition.Substring(1, 1) == "=")
            {
                _operator += "=";
                _condition = Condition.Substring(2);
            }
            else
            {
                _condition = Condition.Substring(1);
            }
            _operator = "=";
            return (dbContext.OrdsRlsds.AsQueryable().Where(FilterColumn + " " + _operator + " " + " @0", _condition).ToList());
        }
        else
        {
            if (Condition.Contains(','))
            {
                string[] conds = Condition.Split(',');
                return (dbContext.OrdsRlsds.AsQueryable().Where(FilterColumn + " >= @0 && " + FilterColumn + " <= @1", conds).ToList());

            }
            else
            {
                return (dbContext.OrdsRlsds.AsQueryable().Where(FilterColumn + " == @0", Condition).ToList());
            }
        }
    }
}

This function uses dynamic query library. At the moment, it filters only one type of records - OrdsRlsds. I need to make this a generic filter so that I can pass any collection and then get the filtered results back.

È stato utile?

Soluzione

Are you using Entity Framework? If so then could you do something like this with generics?

public static IList<T> ParseExpression<T>(string Condition, string FilterColumn) where T:class
{
  var query = dbContext
              .CreateObjectSet<T>()
              .AsQueryable();

  //add filters etc.

  return query.ToList();
}

You would then have to pass the required entity type as a type argument to your method like this:

FilterRecords.ParseExpression<OrdsRlsd>(condition, filterColumn);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top