你可以使用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的值输出相应的消息


原文地址: http://www.cveoy.top/t/topic/iTbM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录