How to get value from IEnumerable collection using its Key?
Asked Answered
N

6

11

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.
      }
}
Nessie answered 24/8, 2015 at 7:7 Comment(4)
Why don't you just use Select method? It's type safe too.Alejoa
items.Select(x=>x.Id) would do it. what are you trying to achieve?Mucilaginous
dynamiclinq.codeplex.comFarewell
If you want to do it in a "generic" way, you can supply a Func<T, bool> selector (predicate) to your method instead of your propertyName argument and then use that in the linq where clause. Same with what you need to select. If it's the whole T item, you don't need a specific select but if you need just a specific property, pass another selector function (of type Func<T, whatever type>)Russi
F
12

// 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);
}
Farewell answered 24/8, 2015 at 7:50 Comment(0)
N
16

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;
}
Nab answered 24/8, 2015 at 7:39 Comment(4)
I don't get c.Id i'm getting c. Equals,GetHashCode,GetType,ToStringNessie
probably because you query on IEnumerable<object> , not IEnumerable<Customer>, try something like customers.OfType<Customer>()Nab
@Neo, I think you need to include using System.Linq. It was giving same problem with me, Worked after I included using System.LinqEspresso
@ArvindKrmar you saved the day my freindNorword
C
14

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 } 
};
Cordon answered 24/8, 2015 at 7:14 Comment(4)
I don't get x.Id i'm getting x. Equals,GetHashCode,GetType,ToStringNessie
Use casting as (Customer)x.Id.Cordon
@Nessie If you will use List<Customer> then now need for any casting otherwise casting needed for anonymous type.Cordon
Very helpful advice to include both methods for obtaining either a collection of customers or a single customer. I only add: if anyone is confused on the advice for typing the IEnumerable object as a List, here's one way that could be done if the object already exists as an IEnumerable: var customers = (objectYourIEnumberableCollectionComesFrom.Customers).ToList(); (basically: just set a variable equal to the IEnumerable collection then cast to list)Emmetropia
F
12

// 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);
}
Farewell answered 24/8, 2015 at 7:50 Comment(0)
D
8

Just use LINQ to achieve what you want to do. if you want to retrieve a specific value you can use where like this:

public Customer GetCustomerById(IEnumerable<Customer> items,int key)
{
    return items.Where(x=>x.id==key)
   .Select(x =>x.Name)
   .First(); 
}

this will retrieve the customer who match a specific Id.

Decennary answered 24/8, 2015 at 7:19 Comment(0)
L
4

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.

Lavonlavona answered 24/8, 2015 at 8:5 Comment(0)
Y
-2
private TextBox [] Collectionstextboxonpanel(Panel panel)
{

    var textBoxspanel1 = panel.Controls.OfType<TextBox>(); // select controls on panle1 by type

    IEnumerable<TextBox> textBoxes = textBoxspanel1; // create collection if need 
    TextBox[] textBoxes1 = textBoxes.ToArray(); // Array collection
    return textBoxes1;                         // get back TextBox Collection
}
Yoakum answered 27/5, 2020 at 13:4 Comment(4)
Hello Igor! Explain in a sentence or two what you did in the code that would be more understandable.Nixon
@Pluto’s point is always a good practice, but it is especially important on these old questions with established answers. Why take this approach over the other five answers?Audreaaudres
Hi i think it's so simple and no need to be coment, actualy you can away var and type just TextBox [] somename = panel1.Controls.Oftype<TextBox>().Toarray(); this you just make collection of allcontrol items located on panel1 with Type ,TextBox> after all you have constant collection ( meaning index will be same and you can manage this for data write/record)Yoakum
the index will be same at all time , after array() , you have constant index. for read or write you don't need to know Textbox Names just create algotimth for take info and write , reading will use the same index.Yoakum

© 2022 - 2024 — McMap. All rights reserved.