c# - Linq 中的通用查询

标签 c# linq generics search

我想在 wpf 中进行通用搜索 UserControl。我希望它获取对象的集合和要搜索的属性的名称。 问题是我无法使用泛型,因为调用搜索函数的代码也无法知道类型。

有办法实现这一点吗?或者某种方式来查询另一种类型下的对象?

最佳答案

考虑这个例子。

interface IFoo
    {

    }
    class Bar1 : IFoo
    {
        //interface implementations
        public string Property1 { get; set; }

        public string myProperty1 { set; get; }
    }

    class Bar2 : IFoo
    {
        //interface implementations
        public string Property1 { get; set; }

        public string myProperty1 { set; get; }
    }


    //Search the list of objects and access the original values.
    List<IFoo> foos = new List<IFoo>();
        foos.Add(new Bar1
        {
            Property1 = "bar1",
            myProperty1 ="myBar1"
        });
        foos.Add(new Bar1());

        foos.Add(new Bar2());
        foos.Add(new Bar2());

        //Get the objects.
        foreach (var foo in foos)
        {
            //you can access foo directly without knowing the original class.
            var fooProperty = foo.Property1;

            //you have to use reflection to get the original type and its properties and methods
            Type type = foo.GetType();
            foreach (var propertyInfo in type.GetProperties())
            {
                var propName = propertyInfo.Name;
                var propValue = propertyInfo.GetValue(foo);
            }
        }


var result = list.Where(a => a.propertyName);

关于c# - Linq 中的通用查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35238238/

相关文章:

c# - 使用线程从子更新父表单

c# - LINQ:如何使用 group by 子句获取 Max Id?

c# - LINQ 中的数据冲突

c# - LINQ 只选择今天当前时间之后的数据

c# - 抽象类型作为方法中的参数(.net、c#)

c# - 如何摆脱警告 "Bot Framework State API is not recommended for production environments, and may be deprecated in a future release."

c# - 在数据模板中绑定(bind)命令 (XF/Prism)

c# - 是否可以使用 json key 而不是 p12 key 来获取服务帐户凭据?

Java 8 自动装箱 + 泛型 : different behaviour with variable vs. 方法

java - Eclipse 中的通用接口(interface)错误