c# - 在C#中查询另一个列表中的列表

标签 c#

我有一个这样的类(class)

public class Tbl
{
    public List<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"];

我该怎么做。

感谢您的每一条评论。

最佳答案

扩展属性不存在,但您可以使用包装器围绕 List<Row>并添加 Indexer property

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"];

关于c# - 在C#中查询另一个列表中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3334021/

相关文章:

c# - Sys.WebForms.PageRequestManagerServerErrorException

c# - 如何循环 SQL 参数列表和 WHERE 子句?或者更有效地获得结果?

c# - epplus 4.1 中取消合并并清除单元格

c# - 返回 RedirectToAction 与返回 Action

c# - 为什么我的委托(delegate)在作为参数传递给方法时不起作用?

c# - 为什么不抛出表达式树中最里面的异常?

c# - 更新后数据集空行

c# - 单元测试项目坚持要求引用 EntityFramework

C#:用于 Url 验证的 RegEx

c# - 为什么 Regex isMatch 为真时给出假?