dimanche 4 mars 2018

Linq+Reflection to get elements from a list by a field name and a condition

I have for example this class:

class SomeClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
    public DateTime Birthdate { get; set; }
}

I need to search in a List all elements that satisfy a condition, for ex. Name == '%th'

//Field name in this example can be:  "Id" , "Name" , "Age" ,"Birthdate"
List<SomeClass> Function(string fieldName, string searchedInfo)
{
    return list.Select(x => (fieldObtainedUsingReflection).Value.ToString().Contains(searchedInfo)).ToList();
}

I know that I can do something like that:

    switch(fieldName)
    {
      case "Id" : 
                 return list.Select(x=>x.Id.ToString().Contains(searchedInfo)).ToList(); 
      case "Name" :
                 return list.Select(x => x.Name.Contains(searchedInfo)).ToList();
     //.....

    }

But I wondered if there is another, more generic implementation.

It's possible to do that using LINQ and Reflection?

If it's possible, what is the time cost if the list has in avg. 30k elements?

Thank you





Aucun commentaire:

Enregistrer un commentaire