TomerAgmon1
TomerAgmon1

Reputation: 295

Generic query in Linq

I want to make a generic search UserControl in wpf. I want it to get a collection of objects and a name of a property to search by. The problem is I can't use generics because the code that calls the search function also can't know of the type.

Is there a way to achieve this? Or some way to query an Object that is underneath another type?

Upvotes: 2

Views: 490

Answers (2)

Bewar Salah
Bewar Salah

Reputation: 567

Consider this example.

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

Upvotes: 1

Łukasz Jankowski
Łukasz Jankowski

Reputation: 81

You can use reflection

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

Upvotes: 1

Related Questions