用于使用枚举集合进行过滤的动态linq表达式

时间:2016-11-17 09:58:54

标签: c# linq enums

public enum StoreType {
    Children = 1,
    Adult = 2,
    Farm = 3
}

如果我有这些的集合:

List<StoreType> enumCollection = new List<StoreType>{ StoreType.Children, StoreType.Farm };

我想构建动态linq表达式,以便我可以通过枚举类型来根据这些枚举过滤结果吗?

伪代码我想要实现的目标:

var enumFilter = LinqExpressionHelper.BuildEnumFilter(enumCollection);
    _storeRepository.GetStores.Where(enumFilter).ToList();

如何构建动态linq表达式,以便我可以通过枚举集合进行过滤?

3 个答案:

答案 0 :(得分:0)

您可以在列表中执行Contains

_storeRepository.GetStores.Where(store => enumCollection.Contains(store.Type)).ToList();

答案 1 :(得分:0)

不确定我理解你想要什么

<p>CONFIRMED</p>

请记住将枚举转换为整数以检索其值

答案 2 :(得分:0)

我认为这就是你想要的:

static class Program
{
    private static void Main(string[] args)
    {
        var enumCollection = new List<StoreType> { StoreType.Children, StoreType.Farm };

        var repo = new StoreRepository();

        var enumFilter = LinqExpressionHelper.BuildEnumFilter(enumCollection);
        var result  = repo.GetStores().Where(enumFilter).ToList();

        foreach (var store in result)
            Console.WriteLine($"Name={store.Name}, Type={store.StoreType}");

        Console.ReadKey();
    }
}

public enum StoreType
{
    Children = 1,
    Adult = 2,
    Farm = 3
}

public class StoreRepository
{
    public IEnumerable<Store> GetStores()
    {
        return new List<Store>
        {
            new Store {Name = "NewYork", StoreType = StoreType.Adult},
            new Store {Name = "RioDeJaneiro", StoreType = StoreType.Farm},
            new Store {Name = "Budapest", StoreType = StoreType.Children}
        };
    }
}

public class Store
{
    public string Name { get; set; }
    public StoreType StoreType { get; set; }
}

public static class LinqExpressionHelper
{
    public static Func<Store, bool> BuildEnumFilter(IEnumerable<StoreType> storeTypes)
    {
        return store => storeTypes.Contains(store.StoreType);
    }
}