如何使用其键从 IEnumerable 集合中获取值?

How to get value from IEnumerable collection using its Key?

我有如下所示的 IEnumerable 集合

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

我想使用键获取值 Id

我试过关注

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.
      }
}

使用LINQ,您可以通过这种方式获取具有特定值的所有客户名称(值):

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

对于单个客户名称,您可以这样做:

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

显然,Id 可以是 1、2 或任何其他。

编辑:

我推荐你 List<Customer> 而不是 Customer[]

所以,

var items = new List<Customer> 
{ 
     new Customer { Name = "test1", Id = 999 }, 
     new Customer { Name = "test2", Id = 989 } 
};

只需使用LINQ 即可实现您想做的事情。如果你想检索一个特定的值,你可以像这样使用 where

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

这将检索匹配特定 ID 的客户。

如果您想通过 Id 从集合中检索 Customer 名称:

public string GetCustomerName(IEnumerable<Customer> customers, int id)
{
    return customers.First(c => c.Id == id).Name;
}

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

// from items collection one by one.

如果我没理解错的话

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);
}

创建列表后要反复查找吗?如果是这样,您可能需要考虑创建一个字典来进行查找,如下所示:

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".

我假设您首先没有创建集合 - 如果您可以控制创建原始集合,您可以首先使用字典。

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
}