获取列表中的项目

时间:2009-08-01 11:42:39

标签: c# list

我有以下列表项

public List<Configuration> Configurations
{
    get;
    set;
}

 public class Configuration
  {
    public string Name
     {
       get;
       set;
     }
    public string Value
      {
       get;
       set;
     }
 }

如何在配置中提取名称=值的项目?

例如:假设我在该列表中有100个配置对象。

我如何获得:Configurations.name [“myConfig”]

那样的东西?

更新:.net v2的解决方案

5 个答案:

答案 0 :(得分:18)

在C#3.0中使用List<T>.Find方法:

var config = Configurations.Find(item => item.Name == "myConfig");

在C#2.0 / .NET 2.0中,您可以使用类似下面的内容(语法可能略有偏差,因为我在很长一段时间内没有以这种方式编写代理......):

Configuration config = Configurations.Find(
    delegate(Configuration item) { return item.Name == "myConfig"; });

答案 1 :(得分:5)

看起来你真正想要的是一个词典(http://msdn.microsoft.com/en-us/library/xfhwa508.aspx)。

字典专门用于映射键值对,并为查找提供比List更好的性能。

答案 2 :(得分:2)

考虑使用词典,但如果不是:


你的问题并不完全清楚,其中一个应该是你的答案。

使用Linq:

var selected = Configurations.Where(conf => conf.Name == "Value");

var selected = Configurations.Where(conf => conf.Name == conf.Value);

如果你想要它在列表中:

List<Configuration> selected = Configurations
    .Where(conf => conf.Name == "Value").ToList();

List<Configuration> selected = Configurations
    .Where(conf => conf.Name == conf.Value).ToList();

答案 3 :(得分:0)

尝试List(T).Find(C#3.0):

string value = Configurations.Find(config => config.Name == "myConfig").Value;

答案 4 :(得分:0)

这是您可以使用的一种方式:

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