Search code examples
c#ienumerableienumerator

How to get value from IEnumerable collection using its Key?


I have IEnumerable collection like following

IEnumerable<Customer> items = new Customer[] 
{ 
     new Customer { Name = "test1", Id = 999 }, 
     new Customer { Name = "test2", Id = 989 } 
};

I want to get value using key Id

I tried like following

public int GetValue(IEnumerable<T> items,string propertyName)
{
      for (int i = 0; i < items.Count(); i++)
      {
           (typeof(T).GetType().GetProperty(propertyName).GetValue(typeof(T), null));
           // I will pass propertyName as Id and want all Id propperty values 
           // from items collection one by one.
      }
}

Solution

  • // I will pass propertyName as Id and want all Id propperty values

    // from items collection one by one.

    If I understand you correctly

    public static IEnumerable<object> GetValues<T>(IEnumerable<T> items, string propertyName)
    {
        Type type = typeof(T);
        var prop = type.GetProperty(propertyName);
        foreach (var item in items)
            yield return prop.GetValue(item, null);
    }