Provide internal list access via named array
I have a class that has an internal list of other objects like so:
public class Parent
{
List<Child> _children;
}
where Child say looks like this:
public class Child
{
public string Name;
}
What I want to do is set up parent where the members of _children can be accessed like so:
...
Child kid = parentInstance["Billy"]; // would find a Child instance
// whose name value is Billy
...
Is this possible?开发者_开发问答 I could obviously do something like this:
Child kid = parentInstance.GetChild("Billy");
But I prefer the array/dictionary like syntax. This isn't a big deal if it isn't, and I don't want to have to jump through a million hoops for what amounts to syntactic sugar.
You could define an indexed property to the Parent
class:
public class Parent
{
List<Child> _children;
public Child this[string name]
{
get
{
return (_children ?? Enumerable.Empty<Child>())
.Where(c => c.Name == name)
.FirstOrDefault();
}
}
}
The "array syntax" is not best suited for what you need, and it's rather obsolete too :)
Nowadays in .net we have Linq and the lambda extension methods, that make our life when working with collections really easy.
You can do:
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
You can also write the above queries in linq syntax instead of lambda. For instance, the first query will be like this:
IEnumerable<Child> childs = from child in parentInstance.Childrens where child.Name == "billy" select child;
精彩评论