[英]Getting an item in a list
I have the following list item 我有以下列表项
public List<Configuration> Configurations
{
get;
set;
}
public class Configuration
{
public string Name
{
get;
set;
}
public string Value
{
get;
set;
}
}
How can I pull an item in configuration where name = value? 如何在配置中提取name = value的项目?
For example: lets say I have 100 configuration objects in that list. 例如:假设我在该列表中有100个配置对象。
How can I get : Configurations.name["myConfig"] 我怎样才能得到:Configurations.name [“myConfig”]
Something like that? 那样的东西?
UPDATE: Solution for .net v2 please 更新:请.net v2的解决方案
Using the List<T>.Find
method in C# 3.0: 使用C#3.0中的
List<T>.Find
方法:
var config = Configurations.Find(item => item.Name == "myConfig");
In C# 2.0 / .NET 2.0 you can use something like the following (syntax could be slightly off as I haven't written delegates in this way in quite a long time...): 在C#2.0 / .NET 2.0中,您可以使用类似下面的内容(语法可能稍微偏离,因为我在相当长的时间内没有以这种方式编写代理...):
Configuration config = Configurations.Find(
delegate(Configuration item) { return item.Name == "myConfig"; });
It seems like what you really want is a Dictionary ( http://msdn.microsoft.com/en-us/library/xfhwa508.aspx ). 看起来你真正想要的是一个词典( http://msdn.microsoft.com/en-us/library/xfhwa508.aspx )。
Dictionaries are specifically designed to map key-value pairs and will give you much better performance for lookups than a List would. 字典专门用于映射键值对,并为查找提供比List更好的性能。
Consider using a Dictionary, but if not: 考虑使用词典,但如果不是:
You question wasn't fully clear to me, one of both should be your answer. 你的问题对我来说并不完全清楚,其中一个应该是你的答案。
using Linq: 使用Linq:
var selected = Configurations.Where(conf => conf.Name == "Value");
or 要么
var selected = Configurations.Where(conf => conf.Name == conf.Value);
If you want it in a list: 如果你想在列表中:
List<Configuration> selected = Configurations
.Where(conf => conf.Name == "Value").ToList();
or 要么
List<Configuration> selected = Configurations
.Where(conf => conf.Name == conf.Value).ToList();
试试List(T).Find (C#3.0):
string value = Configurations.Find(config => config.Name == "myConfig").Value;
Here's one way you could use: 这是您可以使用的一种方式:
static void Main(string[] args)
{
Configuration c = new Configuration();
Configuration d = new Configuration();
Configuration e = new Configuration();
d.Name = "Test";
e.Name = "Test 23";
c.Configurations = new List<Configuration>();
c.Configurations.Add(d);
c.Configurations.Add(e);
Configuration t = c.Configurations.Find(g => g.Name == "Test");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.