【问题标题】:Generic query in LinqLinq 中的通用查询
【发布时间】:2016-02-06 06:47:26
【问题描述】:

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

有没有办法做到这一点?或者以某种方式查询位于另一种类型下的对象?

【问题讨论】:

  • "和一个属性的名称"什么属性?
  • 搜索所依据的属性。例如,如果我搜索 Person,我将传递“全名”的属性名称。

标签: c# linq generics search


【解决方案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);

【讨论】:

  • 我知道如果所有类都派生自同一个空接口,我可以在不知道类型的情况下访问该对象。但是 List.Where() 表达式仍然不起作用
  • @TomerAgmon1,我写的那个不包含Where()。您可以毫无问题地使用它,并且我测试过它可以正常工作。
  • 只要使用 Refection,就可以得到所有类型及其属性和方法。
  • 因此,它没有回答我的问题。您能否详细说明使用 Where 方法?
  • 我不确定你是否理解。我想通过作为输入给出的属性过滤列表。我了解如何通过输入获取属性的名称,但是如何使用 Where 过滤列表?上面给我的例子不起作用
【解决方案2】:

你可以使用反射

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

【讨论】:

  • 通过使用 p.Name.Equals 您假设 p 是一个具有名为 name 的属性的类,并且您只搜索它。正如我所解释的,为了它是通用的,p 是一个对象,并且要搜索的属性只有通过字符串的名称才被我知道
  • 如果我理解正确:.GetType().GetProperty("name").GetValue(foo)
  • 这行得通吗?我会试一试的。另外,上例中的数据是 IQueriable 吗?如果我有一个列表,我会这样做:List.AsQueriable().GetType....?
  • 逻辑不错,但是代码不行。第一个 d. GetType() 返回对象,它没有我关心的属性。但是,如果我将其更改为所有类都从其派生的接口,它就可以工作。即使这样,查询也不返回任何内容。如果我用 (Data[0]) 替换 lambda 表达式中的“d”,它确实有效......这意味着你的示例语法中的某些内容是错误的
猜你喜欢
  • 1970-01-01
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多