C#中findindex使用方法

2025-04-24 18:12:25
推荐回答(3个)
回答1:

// 学生类
class Stu
{
        public string Name { get; set; }
        public int Age{get;set;}
}

//泛型列表
List list = new List();
list.Add(new Stu(){Name="zhang", Age=20});
list.Add(new Stu(){Name="Li", Age=20});
list.Add(new Stu(){Name="Wang", Age=20});
list.Add(new Stu(){Name="Liu", Age=20});

//FindIndex
int index = list.FindIndex(s=>s.Name=="Liu");  //index = 3;
index = list.FindIndex(s=>s.Name=="Li");  //index = 1;

FindIndex的参数是一个Lamda表达式。例如

s=>s.Name=="Li"

的意思是,在列表中找出满足姓名是Li的对象在列表中的索引

回答2:

private struct 定义结构 { public string 学号; public string 姓名; public int 成绩; }
定义结构 构成 = new 定义结构();
List<定义结构> 结构 = new List<定义结构>();
构成.学号 = "001";
构成.姓名 = "万维网";
构成.成绩 = 99;
结构.Add(构成);
构成.学号 = "002";
构成.姓名 = "万维";
构成.成绩 = 98;
结构.Add(构成);
int 序 = 结构.FindIndex(aa => aa.姓名 == "万维");
序 = 结构.FindIndex(aa => aa.姓名 == "万维网");

回答3:

int maxScore = list.Max(s => s.Score);
int index = list.FindIndex(s => s.Score== maxScore);

先用Max函数找出Score(语文成绩)最大的分数,再调用FindIndex查找到索引。