vendredi 20 janvier 2017

How to dynamically get a property value in which is in another property with Linq where statement

I have found some direction for this problem but have not found anything which I can apply to this problem.

I want to filter lists of different types by stated properties they hold. I can use linq to dynamically filter a List by Test.id but I cant manage to filter a List through MyClass.Name

I have these classes.

public class Test
{
    public int Id { get; set; }
    public MyClass myclass { get; set; }
}

public class MyClass
{
    public string Name { get; set; }
}

This is what I'm trying to do.

static void Main(string[] args)
{             
    var source = new List<Test> {
        new Test { Id = 1,myclass = new MyClass() { Name = "bob" } },
        new Test { Id = 2,myclass= new MyClass() { Name = "joe" } } };

    var x = myFilter(source,"Name", "bob");
    Console.WriteLine(x.Count());
}

public static IEnumerable<T> myFilter<T>(List<T> source, string propertyName, string searchString)
{
// get the myclass property then the stated property(Name) value within it
    searchString = searchString.ToLower();
    return source.Where(s => (s.GetType().GetProperty("myclass")
                                .GetType().GetProperty(propertyName)
                                .GetValue(s.GetType().GetProperty("myclass"),null).ToString() ?? " ")
                                .ToLower().Contains(searchString));
}





Aucun commentaire:

Enregistrer un commentaire