简体   繁体   中英

How can I send where statements to a method which are dynamically executed in a LINQ statement?

In the following example, GetFilteredCustomers() works fine so I can send various letters which I want customers to have in their last name.

But how can I build GetFilteredCustomersDynamic() which will enable me to send a full where clause that can be dynamically included in the LINQ statement?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestDynamicLinq2343
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = Customer.GetCustomers();

            //semi-dynamic
            foreach (var customer in Customer.GetFilteredCustomers(customers,  "o"))
            {
                Console.WriteLine(customer.LastName);
            }

            //fully-dyanmic (can send where clauses)
            foreach (var customer in Customer.GetFilteredCustomersDynamic(customers, c => c.FirstName.Contains("a")))
            {
                Console.WriteLine(customer.LastName);
            }

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { FirstName = "Jim", LastName = "Jones" });
            customers.Add(new Customer { FirstName = "Joe", LastName = "Adams" });
            customers.Add(new Customer { FirstName = "Jake", LastName = "Johnson" });
            return customers;
        }

        public static List<Customer> GetFilteredCustomers(List<Customer> customers, string letter)
        {
            return (from c in customers
                    where c.LastName.Contains(letter)
                    select c).ToList();
        }

        public static List<Customer> GetFilteredCustomersDynamic(List<Customer> customers, Func<..., bool> whereClause)
        {
            return (from c in customers
                    where ...whereClause...
                    select c).ToList();
        }

    }
}

Answer:

thanks elder_george and arjuns, I got this example to work like this (albeit without the Expression<> ):

using System;
using System.Collections.Generic;
using System.Linq;

namespace TestDynamicLinq2343
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = Customer.GetCustomers();

            Func<Customer, bool> whereClause = c => c.LastName.Contains("a") && c.FirstName.Contains("J");

            foreach (var customer in Customer.GetFilteredCustomers(customers, whereClause))
            {
                Console.WriteLine(customer.LastName);
            }

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { FirstName = "Jim", LastName = "Jones" });
            customers.Add(new Customer { FirstName = "Joe", LastName = "Adams" });
            customers.Add(new Customer { FirstName = "Jake", LastName = "Johnson" });
            customers.Add(new Customer { FirstName = "Angie", LastName = "Reckar" });
            customers.Add(new Customer { FirstName = "Jean-Luc", LastName = "Beaudoir" });
            return customers;
        }

        public static List<Customer> GetFilteredCustomers(List<Customer> customers, Func<Customer, bool> whereClause)
        {
            return customers
                   .Where(whereClause).ToList();
        }

    }
}

You'd need to represent filter as Expression<Func<Customer, bool>> , not as Func<Customer, bool> . This way you can use Queryable.Where method to add this filter to LINQ expression tree.

EDIT: I was wrong, as this code uses LINQ to objects, where delegates are proper filter criteria. My bad.

Eg (corrected to using normal delegates):

    public static List<Customer> GetFilteredCustomersDynamic(List<Customer> customers, Func<Customer, bool> whereClause)
    {
        return customers
               .Where(whereClause).ToList();
    }

    public static List<Customer> GetFilteredCustomers(List<Customer> customers, string letter)
    {
        return GetFilteredCustomersDynamic(c => c.LastName.Contains(letter));
    }

Try this code,

public static List<Customer> GetFilteredCustomersDynamic(List<Customer> customers, Expression<Func<Customer, bool>> whereClause)
    {
        return customers.Where(whereClause.Compile()).ToList();

    }

@elder_george, there is a typo, expression should be compiled to get it's delegate otherwise this can no compile.

return customers
           .Where(whereClause).ToList();

should be read as

return customers
           .Where(whereClause.Compile()).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM