C#新手求助:如何关联用户评分与对应项目并输出列表字符串
解决方案
一、显示最低分对应的项目
你需要把项目名称和评分关联存储,比如用Dictionary<string, int>或者自定义类,这样就能通过评分反向找到对应的项目。示例代码如下:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // 用键值对存储项目名称和对应评分 var projectScores = new Dictionary<string, int>(); Console.WriteLine("请输入take的评分:"); projectScores["take"] = int.Parse(Console.ReadLine()); Console.WriteLine("请输入take2的评分:"); projectScores["take2"] = int.Parse(Console.ReadLine()); Console.WriteLine("请输入take3的评分:"); projectScores["take3"] = int.Parse(Console.ReadLine()); // 计算基础统计值 double average = projectScores.Values.Average(); int maxScore = projectScores.Values.Max(); int minScore = projectScores.Values.Min(); // 找到最低分对应的第一个项目 string minScoreProject = projectScores.First(p => p.Value == minScore).Key; // 输出结果 Console.WriteLine($"平均值:{average:F2}"); Console.WriteLine($"最高分:{maxScore}"); Console.WriteLine($"最低分:{minScore},对应项目:{minScoreProject}"); } }
如果存在多个项目同分最低分的情况,可以筛选出所有符合条件的项目:
var minScoreProjects = projectScores.Where(p => p.Value == minScore).Select(p => p.Key); Console.WriteLine($"最低分:{minScore},对应项目:{string.Join(", ", minScoreProjects)}");
二、根据指定整数从列表输出对应字符串
注意C#列表的索引是从0开始的,若用户输入的是1-based序号(比如输入1对应第一个项目),需要做转换;若直接用0-based索引,直接取值即可。示例代码:
using System; using System.Collections.Generic; class Program { static void Main() { var projectList = new List<string> { "take", "take2", "take3" }; Console.WriteLine("请输入要获取的项目序号(1-3):"); if (int.TryParse(Console.ReadLine(), out int inputNum)) { // 转换为0-based索引 int index = inputNum - 1; if (index >= 0 && index < projectList.Count) { Console.WriteLine($"对应的项目:{projectList[index]}"); } else { Console.WriteLine("输入的序号超出范围,请输入1-3之间的整数"); } } else { Console.WriteLine("请输入有效的整数"); } } }
若需求是输入整数直接对应列表索引(比如输入0返回第一个项目),去掉inputNum - 1的转换即可,但务必做好范围检查,避免索引越界异常。
内容的提问来源于stack exchange,提问作者NIA BIM
相关产品推荐
相关产品推荐

