2009-08-01 54 views
7

一個項目,我有以下列表項獲取列表中的

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

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

我怎樣才能在配置上拉項目,其中name =價值?

例如:可以說我在該列表中有100個配置對象。

我如何獲得:Configurations.name [ 「的myconfig」]

類似的東西?

UPDATE:解決方案.NET V2請

回答

16

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

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

將這項工作在.NET V2? – 2009-08-01 11:47:09

+0

感謝格雷格,正是我想知道的,這是確定的記憶智慧,使用委託? – 2009-08-01 11:49:18

0

嘗試List(T).Find(C#3.0):

string value = Configurations.Find(config => config.Name == "myConfig").Value; 
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(); 
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"); 
     }