Passing IQueryable as a parameter

I have a class to which I want to pass a list of data. I want this class

  • returns a list of suppliers in the entire data set
  • filter the data by the condition that I have as a parameter, and return the filtered results as a second enumerated list.

I added the condition IQueryableas pseudo code for what I would like to achieve. Is it possible?

internal class Problem
{
    public IEnumerable<Vendor> Vendors { get; set; }
    public IEnumerable<Class1> ReturnedData { get; set; }

    public Problem(List<Class1> data, IQueryable condition)
    {
        Vendors = data.SelectMany(d => d.Vendors).Select(v => v.VendorName).Distinct().Select(v => new Vendor {VendorName =  v}).ToList();

        ReturnedData = data.AsQueryable().Where(condition);
    }
}

internal class Class1
{
    public IEnumerable<Vendor> Vendors { get; set; }
    // lots of other stuff
}

internal class Vendor
{
    public object VendorName { get; set; }
}
+4
source share
3 answers

I will do it a little differently.

First install the nuget System.Linq.Dynamic package

Install-Package System.Linq.Dynamic

After that, `IQueryable Where function will support the string as a parameter. So you can do this:

protected static IQueryable<T> ApplyGridFilter<T>(IQueryable<T> query)
{
            var qText = "id == 1";

            query = query.Where(qText);
            return query;
}

, Func<Class1, bool>>

+3

IQuerable<T>.Where() , , IQueryable,

public Problem(List<Class1> data, Expression<Func<Class1, bool>> condition)
{
    Vendors = data.SelectMany(d => d.Vendors).Select(v => v.VendorName).Distinct()
                  .Select(v => new Vendor {VendorName =  v}).ToList();

    ReturnedData = data.AsQueryable().Where(condition);
}

Problem:

var problemInstance = new Problem(data, x => x.VendorName == "Rob");
+2

I would prefer to use only the delegate as an input parameter and implement the filter logic in the calling class

    class Problem{
        public Problem(data, Func<data, IEnumerable<Class1>> delegate){
              ReturnedData = delegate(data);
        }
     }

var problem = new Problem(data, ds => ds.where(d => d.name =="xyz").tolist());
+2
source

Source: https://habr.com/ru/post/1650820/


All Articles