Linq 中的泛型查询

本文关键字:查询 泛型 Linq | 更新日期: 2023-09-27 18:33:24

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

有没有办法实现这一目标?或者某种方法可以查询另一种类型下的对象?

Linq 中的泛型查询

考虑这个例子。

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);

您可以使用反射

namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {
        var Data = new List<object>() { new A() { MyProperty = "abc" }, new B() { MyProperty = "cde"} };
        var Result = Data.Where(d => (d.GetType().GetProperty("MyProperty").GetValue(d) as string).Equals("abc"));
        // Result is IEnumerable<object> wich contains one A class object ;)
    }
}
class A
{
    public string MyProperty { get; set; }
}
class B
{
    public string MyProperty { get; set; }
}
}