Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
      }
}
like image 999
Neo Avatar asked Aug 24 '15 07:08

Neo


4 Answers

Do you want to look things up repeatedly after creating the list? If so, you might want to consider creating a dictionary to do the lookups, like so:

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

var lookup = items.ToDictionary(itemKeySelector => itemKeySelector.Id);

var result = lookup[989];

Console.WriteLine(result.Name); // Prints "test2".

I'm assuming that you don't create the collection in the first place - if you had control over creating the original collection you could use a dictionary in the first place.

like image 150
Matthew Watson Avatar answered Sep 20 '22 00:09

Matthew Watson


Using LINQ you can get all customers names (values) having specific value in this way:

var valuesList = items.Where(x => x.Something == myVar).Select(v => v.Name).ToList();

For single customer name you can do this:

var singleName = items.FirstOrDefault(x => x.Id == 1)?.Name;

Obviously, the Id can be 1, 2 or any other.

Edit:

I recommend you List<Customer> instead of Customer[]

So,

var items = new List<Customer> 
{ 
     new Customer { Name = "test1", Id = 999 }, 
     new Customer { Name = "test2", Id = 989 } 
};
like image 27
NASSER Avatar answered Nov 02 '22 23:11

NASSER


If you want to retrieve a Customer name from a collection by its Id:

public string GetCustomerName(IEnumerable<Customer> customers, int id)
{
    return customers.First(c => c.Id == id).Name;
}
like image 15
w.b Avatar answered Nov 03 '22 01:11

w.b


// 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);
}
like image 11
Eser Avatar answered Nov 02 '22 23:11

Eser