【问题标题】:C# How to Access a Specific Index of a List of classesC#如何访问类列表的特定索引
【发布时间】:2014-11-05 13:30:12
【问题描述】:

我创建了一个名为studentRecord 的类,它包含多个属性,例如Student Number, First Name, Last Name, Courses, and Credit Hours,用于跟踪个别学生的记录。我还创建了一个名为List<studentRecord> lstRecords = new List<studentRecord>();list,用于存储各种对象(学生)。

我了解通过使用lstRecords.Add(); 添加student 对象,但在编辑对象时遇到了麻烦。用户应该能够输入学生编号,然后能够访问和编辑该对象的特定实例的属性。我想出了这个代码:

StudentRecord editRecord = lstRecords.Find(indexRecord => 
                    indexRecord.intStudentNumber == intChosenRecord);

(顺便说一句,intChosenRecord 是我声明的一个变量,用于跟踪他们正在寻找的索引)

我知道StudentRecord 正在声明一个该类型的新对象,而editRecord 是我的新对象的名称。但是,我在使用 .Find() 方法时遇到了问题。我意识到.Find() 在列表中搜索以找到与输入匹配的 something。因此,我假设intChosenRecord 是程序正在搜索的内容。

但是,我不知道indexRecord 是什么!这是唯一一次在代码中使用它,我可以将其更改为我想要的任何名称而不会出错。有人能解释一下这段代码的作用吗?indexRecord 是什么?

【问题讨论】:

标签: c# list class


【解决方案1】:

“indexRecord”是一个变量,对应于列表中的每个学生。 一旦“=>”右侧的条件(或“谓词”)为真,“查找”就会停止并返回当前学生。 因此,你可以随意命名,只要在“=>”左右使用相同的名称

类似的循环可能是:

StudentRecord editRecord = null;

foreach(var indexRecord in lstRecords)
{                   
    if(indexRecord.intStudentNumber == intChosenRecord))
    {
        editRecord = indexRecord;
        break; // Exits the loop.
    }
}

这段代码不是很干净,但为了清楚起见,我给出它,因为它与你的“oldschool”循环相同,这对你来说肯定更熟悉。

有关此语法的更多详细信息,请参阅http://msdn.microsoft.com/fr-fr/library/bb397687.aspxhttp://msdn.microsoft.com/fr-fr/library/bb397926.aspx 用于“查找”以外的其他方法。

【讨论】:

  • 哦,有道理。谢谢!
【解决方案2】:

indexRecord 是 lambda 表达式的参数。它可以有任何你想要的名字。在您的情况下,它代表StudentRecord(您的列表中的一个元素)

您可以通过以下方式轻松更改代码:

StudentRecord editRecord = lstRecords.Find(x => x.intStudentNumber == intChosenRecord);

您可以在许多网站上了解更多关于 lambda 表达式的信息,例如 http://www.dotnetperls.com/lambda

【讨论】:

    【解决方案3】:

    变量editRecord 指的是Find() 返回的匹配项,因此它不会创建任何新对象或任何新实例;它指的是现有实例。

    indexRecord 视为用于迭代集合中所有项目的标识符,就像您说的那样:

    var numbers = new List<int>();
    foreach (var n in numbers)
    {
        // do something with n
    }
    

    您可以将 n 或 indexRecord 替换为您喜欢的任何标识符。

    【讨论】:

      【解决方案4】:

      当您使用“=>”时,您使用的是lambda expression

      在您的情况下,“indexRecord”是 lambda 表达式“indexRecord.intStudentNumber == intChosenRecord”的输入参数的变量名称。并且 indexRecord 对应于存储在您列表中的一个学生。

      我建议您熟悉 lambda 表达式,因为它是 c# 的一个强大且常用的功能。

      【讨论】:

      • 谢谢你!这很有帮助
      【解决方案5】:

      试试这个..

      List<int> idlist=lstRecords.select(t=>t.intStudentNumber).toList();
      int index=idlist.indexof(intChosenRecord);
      studentRecord record=lstRecords[index];
      

      我总是用这个...

      【讨论】:

      • 此答案已被自动标记为低质量,因为代码没有解释,可能会被删除。请添加说明。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多