2010-06-23 80 views
2

我有了其他的对象,像这样的内部列表类:通过命名阵列提供内部列表访问

public class Parent 
{ 
    List<Child> _children; 
} 

其中儿童说看起来像这样:

public class Child 
{ 
    public string Name; 
} 

我想什么do设置父母,可以像这样访问_children的成员:

... 
Child kid = parentInstance["Billy"]; // would find a Child instance 
            // whose name value is Billy 
... 

这可能吗?我显然可以做这样的事情:

Child kid = parentInstance.GetChild("Billy"); 

但我更喜欢数组/字典像语法。如果不是这样的话,这并不是什么大不了的事情,我不想为了语法上的糖而跳过一百万圈。

回答

7

你可以定义一个indexed propertyParent类:

public class Parent 
{ 
    List<Child> _children; 

    public Child this[string name] 
    { 
     get 
     { 
      return (_children ?? Enumerable.Empty<Child>()) 
       .Where(c => c.Name == name) 
       .FirstOrDefault(); 
     } 
    } 
} 
+0

哎呀我慢打字技能:( – SirDemon 2010-06-23 14:14:43

+1

该死不过多久,他们让你等待接受一个答案,现在仍然太长之前... :) – 2010-06-23 14:20:55

+0

应注意如果你有两个名字相同的孩子,你就是SOL在访问第二个孩子。 – 2010-06-23 14:24:05

0

的“数组的语法”是不是最适合你需要什么,这是相当陈旧太:)

如今在.NET我们有Linq和lambda扩展方法,这使得我们在处理集合时的生活变得非常简单。

你可以这样做:

IEnumerable<Child> childs = parentInstance.Childrens.Where(child => child.Name == "Billy"); //this will get all childs named billy 

Child child = parentInstance.Childrens.FirstOrDefault(child => child.Name == "Billy"); //this will get the first child named billy only, or null if no billy is found 

你也可以写在LINQ的语法,而不是拉姆达上述查询。例如,第一个查询将是这样的:

IEnumerable<Child> childs = from child in parentInstance.Childrens where child.Name == "billy" select child; 
+1

是的,我熟悉linq,喜欢它,并且使用它的小便。不过,对于你打算工作的内容,我不得不公开我想避免的_children列表。 (请注意_children在原始代码中是私有的。) – 2010-06-23 14:19:22

+0

问题不是关于适合在列表中找到项目的最佳方法。他特别询问了“数组语法”或索引器。 – SirDemon 2010-06-23 14:22:00

+0

我知道他要求“数组语法”,但我认为暗示可能更好的做法并不是犯罪。 – 2010-06-23 14:27:14