Linq中的通用查询

时间:2016-02-06 06:47:26

标签: c# linq generics search

我想在wpf中进行通用搜索UserControl。我想让它获取一组对象和一个要搜索的属性的名称。 问题是我不能使用泛型,因为调用搜索功能的代码也不能知道类型。

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

2 个答案:

答案 0 :(得分:1)

您可以使用反射

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

答案 1 :(得分:1)

考虑这个例子。

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