You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#7.3下关联双数组含重复值的前三排名实现求助

C#7.3 实现含并列的前三排名展示方案

针对你需要从两个索引对应数组中提取含并列高值的前三排名需求,这里提供适配C#7.3的具体实现方案:

核心思路

  1. 将分数数组与名称数组按索引配对,保证一一对应关系
  2. 按分数从高到低排序
  3. 确定第三高的分数值(如果不同分数不足3个,则取最低的不同分数)
  4. 筛选出所有分数大于等于第三高值的元素,自然包含所有并列的高排名项

代码实现

using System;
using System.Linq;

class HoundRanker
{
    static void Main()
    {
        // 示例输入数组
        int[] score_SUM = { 10, 5, 10, 6, 1 };
        string[] houndname = { "旺财", "来福", "阿黄", "小黑", "小白" };

        // 1. 配对分数与名称,按分数降序排序
        var sortedScoreNamePairs = score_SUM
            .Zip(houndname, (score, name) => (Score: score, Name: name))
            .OrderByDescending(pair => pair.Score)
            .ToList();

        if (!sortedScoreNamePairs.Any())
        {
            Console.WriteLine("无有效数据");
            return;
        }

        // 2. 获取所有不重复的分数并降序排列
        var distinctSortedScores = sortedScoreNamePairs
            .Select(pair => pair.Score)
            .Distinct()
            .OrderByDescending(score => score)
            .ToList();

        // 3. 确定第三高的分数(处理分数种类不足3的情况)
        int thresholdScore = distinctSortedScores.Count >= 3 
            ? distinctSortedScores[2] 
            : distinctSortedScores.Last();

        // 4. 筛选出符合条件的排名项
        var topRankedItems = sortedScoreNamePairs
            .Where(pair => pair.Score >= thresholdScore);

        // 输出结果
        Console.WriteLine("前三排名(含并列):");
        foreach (var item in topRankedItems)
        {
            Console.WriteLine($"名称:{item.Name},分数:{item.Score}");
        }
    }
}

代码说明

  • 用Zip方法将两个数组按索引配对,C#7.3原生支持命名元组(Score: score, Name: name),保证配对关系清晰
  • 通过Distinct和排序获取不重复的分数序列,以此确定排名阈值,避免遗漏并列项
  • 边界情况处理:空数组、分数种类不足3种的场景都能正常输出

比如你给出的示例输入,运行后会输出:

前三排名(含并列):
名称:旺财,分数:10
名称:阿黄,分数:10
名称:小黑,分数:6

完全符合你的需求。

内容的提问来源于stack exchange,提问作者Alan Dong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:15:40