C# LINQ 取数组/列表 取出最大的N个值的数组索引

这篇博客介绍了如何利用C#的LINQ和Lambda表达式来从浮点数数组中快速获取前N个最大值。通过示例代码展示了两种不同的实现方式,一种是通过OrderByDescending和Take,另一种是使用匿名类型和Select。这些方法在处理大数据集时提供了高效的解决方案。

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

            float[] arr = new float[] {1,2,3,4,5,5,6,3,4,5,6,7,7,8,4,4,3,10,20,3,30,45,5 };
            var b = arr.Select((item, indx) => new { Item = item, Index = indx }).OrderByDescending(x => x.Item).Select(x => x.Index).Take(5).ToArray();

 取前N个最大值

           float[] arr = new float[] {1,2,3,4,5,5,6,3,4,5,6,7,7,8,4,4,3,10,20,3,30,45,5 };
            var b = (from a in arr orderby a descending select a).Take(5).ToArray();

 

C#中,要找出double类数组最大的前30个元素的索引,可以使用以下步骤: 1. 创建一个包含数组元素及其原始索引的元组列表。 2. 对这个列表按照元素进行降序排序。 3. 从排序后的列表中提前30个元素的索引。 以下是实现这一功能的示例代码: ```csharp using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // 示例数组 double[] array = { 1.5, 3.2, 7.8, 4.6, 9.0, 2.1, 5.5, 6.3, 8.4, 0.9, 10.1, 11.3, 12.5, 13.7, 14.9, 15.0, 16.2, 17.4, 18.6, 19.8, 20.0, 21.2, 22.4, 23.6, 24.8, 25.0, 26.2, 27.4, 28.6, 29.8, 30.0, 31.2, 32.4, 33.6, 34.8, 35.0 }; // 获最大的前30个元素的索引 int[] top30Indices = GetTopNIndices(array, 30); // 输出结果 Console.WriteLine("最大的前30个元素的索引:"); foreach (var index in top30Indices) { Console.WriteLine(index); } } static int[] GetTopNIndices(double[] array, int n) { // 创建包含元素及其索引的元组列表 var elementsWithIndices = array .Select((value, index) => new { Value = value, Index = index }) .OrderByDescending(x => x.Value) // 按降序排序 .Take(n) // 前n个元素 .ToArray(); // 提索引返回 return elementsWithIndices.Select(x => x.Index).ToArray(); } } ``` ### 解释: 1. **创建元组列表**:使用`Select`方法将数组中的每个元素和它的索引组合成一个元组列表。 2. **排序**:使用`OrderByDescending`方法按元素进行降序排序。 3. **提前n个元素**:使用`Take`方法取出前30个元素。 4. **提索引**:使用`Select`方法从元组中提取出索引。 这样,你就可以得到数组最大的前30个元素的索引了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有道无术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值