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

C#生成带随机值的Mugg对象并按评分降序排序问题求助

Mugg对象列表按评分降序排序问题解决

问题描述

需要创建30个包含Motiv、Typ、Snittbetyg(评分)、Pris(价格)字段的Mugg对象,每个对象字段值组合需唯一,之后按Snittbetyg降序排序。当前代码能生成30个对象,但无法实现排序,相关代码如下:

循环生成代码

for (int i = 0; i < 30; i++)
{
    List<string> Motiv = new List<string> { "Harry Potter", "Djur", "Världens bästa", "Kärlek" };
    List<string> Typ = new List<string> { "Kaffemugg", "Resemuggar", "Termo", "Ölmugg" };

    Random random = new Random();

    int snittbetyg = random.Next(0, 10);
    int pris = random.Next(100, 499);
    int getRdnMotiv = random.Next(Motiv.Count);
    int getRdnTyp = random.Next(Typ.Count);

    List<Mugg> muggList = new List<Mugg>();
    muggList.Add(new Mugg() { Motiv = Motiv[getRdnMotiv], Typ = Typ[getRdnTyp], Snittbetyg = snittbetyg, Pris = pris });

    List<Mugg> sortByRating = muggList.OrderBy(user => user.Snittbetyg).ToList();
    foreach (Mugg mugg in sortByRating)

        Console.WriteLine($"Mugg {i + 1}: " + "Motiv = " + mugg.Motiv + ", Typ = " + mugg.Typ + ", Snittbetyg = " + mugg.Snittbetyg + ", Pris = " + mugg.Pris);
}

Mugg类代码

class Mugg
{
    public string Motiv { get; set; }
    public string Typ { get; set; }
    public int Snittbetyg { get; set; }
    public int Pris { get; set; }
}

问题分析

  1. 列表初始化位置错误:每次循环新建muggList,导致每次仅添加一个对象,排序操作仅针对单个元素,完全无效。
  2. Random实例化位置错误:循环内重复创建Random,会因系统时钟精度问题生成重复随机值。
  3. 排序方向错误:使用OrderBy是升序排序,需用OrderByDescending实现降序。
  4. 未处理对象唯一性:原代码未校验对象字段组合,可能生成重复的Mugg对象。

修正后的代码

完整实现代码

using System;
using System.Collections.Generic;
using System.Linq;

class Mugg
{
    public string Motiv { get; set; }
    public string Typ { get; set; }
    public int Snittbetyg { get; set; }
    public int Pris { get; set; }

    // 重写方法用于判断对象是否唯一
    public override bool Equals(object obj)
    {
        if (obj is Mugg other)
        {
            return Motiv == other.Motiv && Typ == other.Typ && Snittbetyg == other.Snittbetyg && Pris == other.Pris;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Motiv, Typ, Snittbetyg, Pris);
    }
}

class Program
{
    static void Main()
    {
        // 提前定义可选值列表,避免重复创建
        List<string> motivOptions = new List<string> { "Harry Potter", "Djur", "Världens bästa", "Kärlek" };
        List<string> typOptions = new List<string> { "Kaffemugg", "Resemuggar", "Termo", "Ölmugg" };
        Random random = new Random();
        List<Mugg> muggList = new List<Mugg>();

        // 生成30个唯一的Mugg对象
        while (muggList.Count < 30)
        {
            string selectedMotiv = motivOptions[random.Next(motivOptions.Count)];
            string selectedTyp = typOptions[random.Next(typOptions.Count)];
            int snittbetyg = random.Next(0, 11); // 生成0-10的评分(包含10)
            int pris = random.Next(100, 500); // 生成100-499的价格(包含499)

            Mugg newMugg = new Mugg
            {
                Motiv = selectedMotiv,
                Typ = selectedTyp,
                Snittbetyg = snittbetyg,
                Pris = pris
            };

            // 检查是否已存在相同对象,不存在则添加
            if (!muggList.Contains(newMugg))
            {
                muggList.Add(newMugg);
            }
        }

        // 按Snittbetyg降序排序
        List<Mugg> sortedMuggs = muggList.OrderByDescending(m => m.Snittbetyg).ToList();

        // 输出排序后的结果
        int count = 1;
        foreach (Mugg mugg in sortedMuggs)
        {
            Console.WriteLine($"Mugg {count}: Motiv = {mugg.Motiv}, Typ = {mugg.Typ}, Snittbetyg = {mugg.Snittbetyg}, Pris = {mugg.Pris}");
            count++;
        }
    }
}

关键修正点说明

  • 实例化优化:将muggList、可选值列表和Random移到循环外,避免重复创建和随机值重复。
  • 排序逻辑调整:在所有对象生成完成后,使用OrderByDescending执行降序排序。
  • 唯一性保证:重写Mugg类的Equals和GetHashCode方法,结合Contains方法确保生成的对象唯一。
  • 随机值范围修正:random.Next(0,11)生成0到10的完整评分范围,Next(100,500)生成符合要求的价格区间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:05:24