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.
      }
}
leppie
  • 115,091
  • 17
  • 196
  • 297
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 1
    Why don't you just use Select method? It's type safe too. – Ufuk Hacıoğulları Aug 24 '15 at 07:10
  • 3
    `items.Select(x=>x.Id)` would do it. what are you trying to achieve? – Sriram Sakthivel Aug 24 '15 at 07:10
  • https://dynamiclinq.codeplex.com/ – Eser Aug 24 '15 at 07:11
  • If you want to do it in a "generic" way, you can supply a Func 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`) – kha Aug 24 '15 at 07:27

6 Answers6

15

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;
}
w.b
  • 11,026
  • 5
  • 30
  • 49
13

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 } 
};
NASSER
  • 5,900
  • 7
  • 38
  • 57
  • I don't get `x.Id` i'm getting `x.` Equals,GetHashCode,GetType,ToString – Neo Aug 24 '15 at 07:43
  • Use casting as `(Customer)x.Id`. – NASSER Aug 24 '15 at 07:44
  • @Neo If you will use `List` then now need for any casting otherwise casting needed for anonymous type. – NASSER Aug 24 '15 at 07:50
  • can you please look into one of my [question](https://stackoverflow.com/questions/55688229/how-to-split-data-table-into-multiple-tables-with-adding-1-minute-delay) related to it? – Moeez Apr 16 '19 at 06:54
  • 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) – Kris Bunda Jan 16 '22 at 16:40
11

// 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);
}
Community
  • 1
  • 1
Eser
  • 12,346
  • 1
  • 22
  • 32
6

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.

Nadeem Khoury
  • 886
  • 6
  • 18
  • can you please look into one of my [question](https://stackoverflow.com/questions/55688229/how-to-split-data-table-into-multiple-tables-with-adding-1-minute-delay) related to it? – Moeez Apr 16 '19 at 06:54
3

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.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
-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
}
Igor
  • 55
  • 1
  • 3
  • 5
    Hello Igor! Explain in a sentence or two what you did in the code that would be more understandable. – Pluto May 27 '20 at 13:26
  • 4
    @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? – Jeremy Caney May 28 '20 at 04:40
  • 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().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) – Igor Jun 02 '20 at 10:38
  • 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. – Igor Jun 02 '20 at 11:48