lundi 24 octobre 2016

How to use Linq with Reflection in C#?

To get the name from id using reflection from an enumerable. I'm using:

foreach(string idValue in Values)
{
    var listSource = itemsSource as IEnumerable;
    PropertyInfo idProperty = listItem.GetType().GetProperty("Id");
    PropertyInfo nameProperty = listItem.GetType().GetProperty("Name");

    foreach (var listItem in listSource)
    {
        if (idValue.Equals(idProperty.GetValue(listItem, null).ToString()))
        {
            value = nameProperty.GetValue(listItem, null).ToString();
            break;
        }
    }
    //do something with value.
}

How to use Linq with reflection, so that I need not loop through elements for each value of 'idValue' in the outer loop??

something like:

reflectionList.Select(x=> x.idProperty == idValue) and use it to get value of nameProperty

Please help.





Aucun commentaire:

Enregistrer un commentaire