如何使用 List过滤强类型列表 变量

发布于 2024-07-23 08:29:01 字数 1581 浏览 2 评论 0原文

我需要使用另一个过滤器名称和值列表来过滤 StaffingPositionsDataContract 类型的强类型列表。 我有这两个列表:

    List<SerializedForm> deserializedObject = JsonConvert.DeserializeObject<List<SerializedForm>>(searchFilters).Where(x => !string.IsNullOrEmpty(x.value) && !string.Equals(x.value.ToUpper(), "ALL")).ToList();
    List<StaffingPositionsDataContract> staffingPositionResponse = new StaffingPositionsDataContract().LoadMockData();

deserializedObject 有 2 个属性。 1:“名称”,2:“值”。 这些属性需要能够过滤具有不同属性的多个不同类。 如果当前正在过滤的 StaffingPositionsDataContract 是字符串,而不是 int、decimal 或 float,我有一个有效的方法。 下面是我正在使用的仅适用于字符串过滤器的内容。

  private static List<T> _GetFilteredList<T, U>(IList<T> ListToFilter, string PropertyToFilterOn, List<U> FilterValues)
    {
        ParameterExpression p = Expression.Parameter(typeof(T), "x");

        Func<T, U> select = Expression.Lambda<Func<T, U>>(
            Expression.Property(p, PropertyToFilterOn), p).Compile();

        return ListToFilter.Join(FilterValues, select, u => u, (t, u) => t).ToList();
    }

这是如何调用的:

 var filteredPositions = staffingPositionResponse;
        deserializedObject.ForEach(delegate(SerializedForm filters)
        {
            filteredPositions = _GetFilteredList<StaffingPositionsDataContract, string>(staffingPositionResponse, filters.name, new List<string> { filters.value });
        });

有人知道如何使用 deserializedObject 对象过滤 StaffingPositionResponse 类吗?

I need to filter a strongly typed list of type StaffingPositionsDataContract, with another list of filter names and values. I have these two lists:

    List<SerializedForm> deserializedObject = JsonConvert.DeserializeObject<List<SerializedForm>>(searchFilters).Where(x => !string.IsNullOrEmpty(x.value) && !string.Equals(x.value.ToUpper(), "ALL")).ToList();
    List<StaffingPositionsDataContract> staffingPositionResponse = new StaffingPositionsDataContract().LoadMockData();

The deserializedObject has 2 properties. 1: "name", 2: "value". These properties need to be able to filter several different classes with different properties. I have a method that works if the StaffingPositionsDataContract currently being filtered is a string, but not int or decimal or float. Below is what I am using that works with string filters only.

  private static List<T> _GetFilteredList<T, U>(IList<T> ListToFilter, string PropertyToFilterOn, List<U> FilterValues)
    {
        ParameterExpression p = Expression.Parameter(typeof(T), "x");

        Func<T, U> select = Expression.Lambda<Func<T, U>>(
            Expression.Property(p, PropertyToFilterOn), p).Compile();

        return ListToFilter.Join(FilterValues, select, u => u, (t, u) => t).ToList();
    }

Here is how that is getting called:

 var filteredPositions = staffingPositionResponse;
        deserializedObject.ForEach(delegate(SerializedForm filters)
        {
            filteredPositions = _GetFilteredList<StaffingPositionsDataContract, string>(staffingPositionResponse, filters.name, new List<string> { filters.value });
        });

Anyone know how I can filter the staffingPositionResponse class with the deserializedObject objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫卆 2024-07-30 08:29:01

这是一个执行类似操作的控制台应用程序。 您必须评估如何从应用程序的表单中获取正确的 json 序列化。 我只是将字典强制转换为 json 字符串以进行测试。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Reflection;

namespace FilterLists
{
    public class Program
    {
        static void Main(string[] args)
        {
            // set up the bunk json
            var filters = new Dictionary<string, object>();
            filters.Add("PositionId", "12345");
            string json = JsonConvert.SerializeObject(filters);
            // what's it look like as a string?
            Console.WriteLine(json);

            // take the json string and stuff it to our method.
            var result = GetStaffingPosition(json);
            Console.WriteLine(result.Count);
        }

    public static List<StaffingPositionsDataContract> GetStaffingPosition(string searchFilters)
    {
        var filters = JsonConvert.DeserializeObject<Dictionary<string, object>>(searchFilters).ToList();
        var contracts = StaffingPositionsDataContract.LoadMockData();

        List<StaffingPositionsDataContract> result = new List<StaffingPositionsDataContract>();

        foreach (var filter in filters)
        {
            foreach (var contract in contracts)
            {
                PropertyInfo info = typeof(StaffingPositionsDataContract).GetProperty(filter.Key);
                var propType = info.PropertyType;

                if (info.GetValue(contract, null).Equals(Convert.ChangeType(filter.Value, propType)))
                {
                    result.Add(contract);
                }
            }
        }

        return result;
    }
}


[Serializable]
public class StaffingPositionsDataContract
{
    public int PositionId { get; set; }
    public string Series { get; set; }
    public string BFY { get; set; }
    public string BudgetStatus { get; set; }
    public string DutyStation { get; set; }
    public string OrgLocation { get; set; }
    public string BudgetingEntity { get; set; }
    public string FieldName { get; set; }

    public static List<StaffingPositionsDataContract> LoadMockData()
    {
        List<StaffingPositionsDataContract> staffingposition = new List<StaffingPositionsDataContract>()
        {
            new StaffingPositionsDataContract() {PositionId = 12345, Series="", BFY="FY2010", BudgetStatus="Actual", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 67891, Series="", BFY="FY2011", BudgetStatus="Actual", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 12345, Series="", BFY="FY2010", BudgetStatus="Projected", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 67892, Series="", BFY="FY2011", BudgetStatus="Projected", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 987654, Series="", BFY="FY2010", BudgetStatus="Projected", DutyStation="", OrgLocation="", BudgetingEntity=""}
        };
        return staffingposition;
    }
}
}

Here's a console app that does something similar. You'll have to evaluate how to get the proper json serialization from your app's form. I'm simply forcing a Dictionary into a json string for testing purposes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Reflection;

namespace FilterLists
{
    public class Program
    {
        static void Main(string[] args)
        {
            // set up the bunk json
            var filters = new Dictionary<string, object>();
            filters.Add("PositionId", "12345");
            string json = JsonConvert.SerializeObject(filters);
            // what's it look like as a string?
            Console.WriteLine(json);

            // take the json string and stuff it to our method.
            var result = GetStaffingPosition(json);
            Console.WriteLine(result.Count);
        }

    public static List<StaffingPositionsDataContract> GetStaffingPosition(string searchFilters)
    {
        var filters = JsonConvert.DeserializeObject<Dictionary<string, object>>(searchFilters).ToList();
        var contracts = StaffingPositionsDataContract.LoadMockData();

        List<StaffingPositionsDataContract> result = new List<StaffingPositionsDataContract>();

        foreach (var filter in filters)
        {
            foreach (var contract in contracts)
            {
                PropertyInfo info = typeof(StaffingPositionsDataContract).GetProperty(filter.Key);
                var propType = info.PropertyType;

                if (info.GetValue(contract, null).Equals(Convert.ChangeType(filter.Value, propType)))
                {
                    result.Add(contract);
                }
            }
        }

        return result;
    }
}


[Serializable]
public class StaffingPositionsDataContract
{
    public int PositionId { get; set; }
    public string Series { get; set; }
    public string BFY { get; set; }
    public string BudgetStatus { get; set; }
    public string DutyStation { get; set; }
    public string OrgLocation { get; set; }
    public string BudgetingEntity { get; set; }
    public string FieldName { get; set; }

    public static List<StaffingPositionsDataContract> LoadMockData()
    {
        List<StaffingPositionsDataContract> staffingposition = new List<StaffingPositionsDataContract>()
        {
            new StaffingPositionsDataContract() {PositionId = 12345, Series="", BFY="FY2010", BudgetStatus="Actual", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 67891, Series="", BFY="FY2011", BudgetStatus="Actual", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 12345, Series="", BFY="FY2010", BudgetStatus="Projected", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 67892, Series="", BFY="FY2011", BudgetStatus="Projected", DutyStation="", OrgLocation="", BudgetingEntity=""},
            new StaffingPositionsDataContract() {PositionId = 987654, Series="", BFY="FY2010", BudgetStatus="Projected", DutyStation="", OrgLocation="", BudgetingEntity=""}
        };
        return staffingposition;
    }
}
}
草莓味的萝莉 2024-07-30 08:29:01

请注意,只有在编译时无法知道属性名称时才应使用此方法; 但以下似乎有效:

public static IEnumerable<T> WhereAny<T, U>(
    this IEnumerable<T> ListToFilter, string PropertyToFilterOn, List<U> FilterValues)
{
    ParameterExpression p = Expression.Parameter(typeof(T), "x");
    var methodCall = Expression.Call(            
        Expression.Constant(FilterValues, typeof(List<U>)),
        typeof(List<U>).GetMethod("Contains"),
        Expression.PropertyOrField(p, PropertyToFilterOn)
    );
    return ListToFilter.Where(Expression.Lambda<Func<T,bool>>(methodCall, p).Compile());
}

Note that you should only use this approach if you cannot know the property names at compile time; but the following seems to work:

public static IEnumerable<T> WhereAny<T, U>(
    this IEnumerable<T> ListToFilter, string PropertyToFilterOn, List<U> FilterValues)
{
    ParameterExpression p = Expression.Parameter(typeof(T), "x");
    var methodCall = Expression.Call(            
        Expression.Constant(FilterValues, typeof(List<U>)),
        typeof(List<U>).GetMethod("Contains"),
        Expression.PropertyOrField(p, PropertyToFilterOn)
    );
    return ListToFilter.Where(Expression.Lambda<Func<T,bool>>(methodCall, p).Compile());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文