C# List根据值找到索引值方法

本文介绍C#中如何使用List的FindIndex方法来查找特定元素的索引,通过示例展示了针对简单整数和对象集合的查找过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

List test = new List();

int index = test .FindIndex(item=>item.Equals(888));

下面是对象集合
int sysIndex = eLists.FindIndex(item => item.GoodsNo.Equals(info.GoodsNo));
var f = eLists[sysIndex];

### C# 获取 List 集合中最大的索引 在C#中,为了获取`List<T>`集合中最大的索引,可以采用多种方式实现这一目标。一种常见的方式是遍历整个列表来比较各个元素并记录当前发现的最大及其对应的索引位置[^2]。 另一种更为简洁的方法则是利用LINQ查询表达式结合`Select`与`MaxBy`函数(适用于.NET Core 3.1及以上版本),这能够更直观地完成相同的操作[^5]: ```csharp using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> values = new List<int>{ 1, 3, 5, 7, 9 }; // 使用 LINQ 查询语法寻具有最大的对象,并通过 Select 投影出其原始索引来获得最大所在的位置。 int maxIndex = values.Select((value, index) => new { value, index }) .MaxBy(item => item.value) ?.index ?? -1; Console.WriteLine($"The index of the maximum element is: {maxIndex}"); } } ``` 对于较旧版本的.NET框架,则可以通过自定义泛型方法来达到同样的效果,这种方法不仅限于整数类型的数组,还可以应用于实现了`IComparable<T>`接口的数据类型[^4]。 ```csharp public static int FindMaxIndex<T>(this IList<T> list) where T : IComparable<T> { if(list == null || list.Count == 0){ throw new ArgumentException("Empty or null list"); } var maxValue = list[0]; var maxIndex = 0; for(var i = 1 ; i < list.Count ; ++i){ if(list[i].CompareTo(maxValue)>0){ maxValue = list[i]; maxIndex = i; } } return maxIndex; } // 调用扩展方法 List<double> doubleValues = new List<double>{ 1.1, 2.2, 3.3, 4.4, 5.5 }; Console.WriteLine(doubleValues.FindMaxIndex()); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值