C# List<Student> 中查找特定姓名元素的下标
你可以使用 List<T>.FindIndex 方法来查找并返回指定条件的元素的下标。以下是一个示例代码:
using System;
using System.Collections.Generic;
public class Student
{
public string Name { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Name = 'John' },
new Student { Name = 'Mary' },
new Student { Name = 'Bob' }
};
int index = students.FindIndex(s => s.Name == '1');
if (index != -1)
{
Console.WriteLine($'Name为1的项的下标为: {index}');
}
else
{
Console.WriteLine('没有找到Name为1的项');
}
}
}
在上面的示例中,我们定义了一个 Student 类,其中包含一个 Name 属性。然后我们创建了一个 List<Student> 对象,并向其中添加了几个 Student 对象。
使用 FindIndex 方法查找 Name 属性等于'1'的项,并将返回的下标存储在 index 变量中。如果找到了匹配的项,index 将是大于等于 0 的值,否则将是 -1。
最后,我们根据 index 的值输出相应的消息。
原文地址: https://www.cveoy.top/t/topic/qzbH 著作权归作者所有。请勿转载和采集!