簡體   English   中英

如何過濾 C# 中動態列和動態屬性的 LINQ 查詢?

[英]How to filter LINQ query on dynamic columns and dynamic property in C#?

我在獲取 LINQ 查詢中的過濾記錄以根據條件和屬性動態檢索列時遇到問題(例如,包含、等於、StartsWith、EndsWith)。

我有一個如下的記錄列表 -

 List<Employee> employees = new List<Employee>()
            {

                new Employee()
                {
                    name ="Andy", cityCriteria="Florida West", state   ="NYC"
                },
                new Employee()
                {
                    name = "John", cityCriteria = "West Virginia", state = "Arizona"
                },
                new Employee()
                {
                    name = "Nichole", cityCriteria = "East Florida", state = "NYC"
                }
            };

所以,這只是一些樣本記錄,數據將來自數據庫,並且會有很多記錄。 現在,我想要實現的是,如果根據列表發布了與城市匹配的任何視頻,我必須通知所有人。 所以,我可以收到通知值作為 City:Florida:startsWith、City:Florida:Equals、City:Florida:Contains 等,也可能有 State 標准。 那么,我如何在列表中動態過濾記錄,例如輸入是否以開頭我應該使用 StartsWith ex

If Input is City:Florida:startsWith --> 
 var result = employees.where(i=>i.CityCriteria.StartsWith("Florida").toList();

If Input is City:Florida:Contains --> 
 var result = employees.where(i=>i.CityCriteria.Contains("Florida").toList();

If Input is City:Florida:EndsWith --> 
 var result = employees.where(i=>i.CityCriteria.EndsWith("Florida").toList();

If Input is City:Florida:Equals --> 
 var result = employees.where(i=>i.CityCriteria.Equals("Florida").toList();

我不想使用多個條件並形成 Where 子句。 我希望它是動態的,就像我收到的開頭應該替換 LINQ 查詢開始、結束、等於等,並且它應該與動態列靈活,就像我必須為 State、國家、Z963AB000D02F11F4DZ1 等應用相同的邏輯

如果可能,請發布一些示例代碼

我希望這可以幫助你:

    private IEnumerable<Employee> FilterDynamically(IEnumerable<Employee> employees, string input, string cityName)
    {
        switch (input.ToLower())
        {
            case "starts with":
                return employees.Where(x => x.cityCriteria.StartsWith(cityName));

            case "ends with":
                return employees.Where(x => x.cityCriteria.EndsWith(cityName));

            case "contains":
                return employees.Where(x => x.cityCriteria.Contains(cityName));

            case "equals":
                return employees.Where(x => x.cityCriteria.Equals(cityName));
            
            default:
                 return Enumerable.Empty<Employee>();
        }
    }

可能有很多解決方案,但通常像構建一個可擴展的解決方案,這在我自己的項目中得到了證明。

//In case of addition filters u just need to update this class and everything will work else where
public class Filters
{        
    Filters() {
        maps.Add("startswith", StartsWith);
        maps.Add("Contains", Contains);
        maps.Add("Endswith", Endswith);
        maps.Add("Equals", Equals);
    }

    public static readonly Filters Instance = new Filters();

    public Func<Employee, string, bool> GetFilter(string filterClause)
        => maps.ContainsKey (filterClause) ? maps[filterClause] : None;

    Func<Employee, string, bool> StartsWith = (e, value) => e.cityCriteria.StartsWith(value);
    Func<Employee, string, bool> Contains = (e, value) => e.cityCriteria.Contains(value);
    Func<Employee, string, bool> Endswith = (e, value) => e.cityCriteria.EndsWith(value);
    Func<Employee, string, bool> Equals = (e, value) => e.cityCriteria.Equals(value);

    //In case none of the filter cluase do not match 
    Func<Employee, string, bool> None = (e, value) => true;

    //Filter clauses are made case insensitive by passing stringcomparer
    Dictionary<string, Func<Employee, string, bool>> maps =
        new Dictionary<string, Func<Employee, string, bool>>(StringComparer.OrdinalIgnoreCase);

}

易於使用和一致性的擴展方法

public static class EmployeeExtensions
{
    public static IEnumerable<Employee> Filter(this IEnumerable<Employee> employees, string filterClause, string filterValue)
        => employees.Where(x => Filters.Instance.GetFilter(filterClause)(x, filterValue));
}

用法如下

public class Usage
{
    public void Test()
    {
        var filteredEmployees = 
            new Employee[0]
            .Filter("startswith", "florida")
            .ToList();
    }
}

獲取屬性值的一個簡單快速的解決方案是使用 DynamicMethod。 這是我的做法,這是一個可行的解決方案:

using Newtonsoft.Json;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;

namespace NUnitTestProject1
{
    public class Tests
    {
        static List<Employee> employees = new List<Employee>()
        {
            new Employee()
            {
                Name = "Andy", City = "Florida West", State = "NYC"
            },
            new Employee()
            {
                Name = "John", City = "West Virginia", State = "Arizona"
            },
            new Employee()
            {
                Name = "Nichole", City = "East Florida", State = "NYC"
            }
        };

        public enum Comparison
        {
            StartsWith,
            EndsWith,
            Equals
        }

        public struct Condition
        {
            public string PropertyName { get; set; }
            public string PropertyValue { get; set; }
            public Comparison Comparison { get; set; }
        }

        [TestCase("City", "Florida", Comparison.StartsWith, "Andy")]
        [TestCase("State", "Arizona", Comparison.Equals, "John")]
        public void TestConditions(string propertyName, string propertyValue, Comparison comparison, string expectedResult)
        {
            string jsonCondition = $"{{\"PropertyName\":\"{propertyName}\",\"PropertyValue\":\"{propertyValue}\",\"Comparison\":{(int)comparison}}}";
            Condition parsedCondition = JsonConvert.DeserializeObject<Condition>(jsonCondition);
            List<Employee> result = new List<Employee>();
            var getter = GetPropertGetter(typeof(Employee).ToString(), parsedCondition.PropertyName);
            switch (parsedCondition.Comparison)
            {
                case Comparison.StartsWith:
                    result = employees.Where(i => (getter(i) as string).StartsWith(parsedCondition.PropertyValue)).ToList();
                    break;
                case Comparison.EndsWith:
                    result = employees.Where(i => (getter(i) as string).EndsWith(parsedCondition.PropertyValue)).ToList();
                    break;
                case Comparison.Equals:
                    result = employees.Where(i => (getter(i) as string).Equals(parsedCondition.PropertyValue)).ToList();
                    break;
            }

            Assert.That(result.FirstOrDefault().Name, Does.Match(expectedResult));
        }

        Func<object, object> GetPropertGetter(string typeName, string propertyName)
        {
            Type t = Type.GetType(typeName);
            PropertyInfo pi = t.GetProperty(propertyName);
            MethodInfo getter = pi.GetGetMethod();

            DynamicMethod dm = new DynamicMethod("GetValue", typeof(object), new Type[] { typeof(object) }, typeof(object), true);
            ILGenerator lgen = dm.GetILGenerator();

            lgen.Emit(OpCodes.Ldarg_0);
            lgen.Emit(OpCodes.Call, getter);

            if (getter.ReturnType.GetTypeInfo().IsValueType)
            {
                lgen.Emit(OpCodes.Box, getter.ReturnType);
            }

            lgen.Emit(OpCodes.Ret);
            return dm.CreateDelegate(typeof(Func<object, object>)) as Func<object, object>;
        }
    }

    internal class Employee
    {
        private string name;
        private string city;
        private string state;

        public string Name { get => name; set => name = value; }
        public string City { get => city; set => city = value; }
        public string State { get => state; set => state = value; }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM