Query a list in another list in C#
I have a class like that
public class Tbl
{
public Lis开发者_JS百科t<Row> Rows {get; set;}
}
public class Row
{
public string Name {get; set;}
public Value {get; set;}
}
//Using the class
//Add rows to Tbl
Tbl t = new Tbl();
t.Rows.Add(new Row() {Name = "Row1", Value = "Row1Value"};
t.Rows.Add(new Row() {Name = "Row2", Value = "Row2Value"};
t.Rows.Add(new Row() {Name = "Row3", Value = "Row3Value"};
//Now I want to select the Row2 in this list, usually, I use this way
public Row GetRow(this Tbl t, string RowName)
{
return t.Rows.Where(x => x.Name == RowName).FirstOrDefault();
}
Row r = t.GetRow("Row2");
//But I would like to use that way
Row r = t.Rows["Row2"];
How can I do that.
Thanks for every comments.
Extension properties do not exist, but you could use a wrapper around List<Row>
and add an Indexer property to it.
public class RowList : List<Row> {
public Row this[string key] {
get { return this.Where( x => x.Name == key ).FirstOrDefault(); }
}
}
public class Tbl
{
public RowList Rows { get; set; }
}
Tbl t = new Tbl();
// ...
Row r = t.Rows["Row2"];
Use a string indexer in yout Tbl class
public Row this[string s]
{
get
{
return Rows.Where(x => x.Name == s).FirstOrDefault();
}
}
Then you use like:
Row r = t["Row2"]
You'll need to add an indexed property to your Tbl
type:
public class Tbl
{
public List<Row> Rows { get; set; }
public Row this[string name]
{
get
{
return Rows.Where(r => r.Name == name).FirstOrDefault();
}
}
}
I think what you need there is an Indexer, which would allow you to do t["Row2"] - I'm not sure how easily you could use that to do t.Rows["Row2"] though.
Add this to your Tbl class:
public Row this[string name] {
get { return Rows.Where(r => r.Name == name).FirstOrDefault(); }
}
精彩评论