C#中从原列表随机抽元素生成含重复的更长列表问题
问题解决:生成含重复元素的随机扩展列表
核心问题分析
你的代码报错根源是类型不匹配:TempListGrappling2是List<TempListGrappling2>类型,但你尝试添加Grappling2[]数组;同时随机索引逻辑存在越界风险(原列表仅2个元素,却生成0-2的索引)。
修正方案
根据需求,我们需要从原列表Grappling2中随机选取元素(允许重复),生成更长的目标列表TempListGrappling2。分两种情况处理:
情况1:目标列表存储Grappling2类型元素
如果TempListGrappling2无需自定义类,直接存储原类型元素:
// 初始化原列表 Grappling2 = new List<Grappling2> { new Grappling2 { ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png", TrainingText = "Iron Gate" }, new Grappling2 { ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png", TrainingText = "Long guard" } }; // 初始化目标列表(类型改为List<Grappling2>) TempListGrappling2 = new List<Grappling2>(); var rand = new Random(); // 生成6个元素的随机列表 for (int counter = 0; counter < 6; counter++) { // 生成0到原列表长度-1的随机索引,避免越界 int ndx = rand.Next(Grappling2.Count); // 从原列表取元素添加到目标列表 TempListGrappling2.Add(Grappling2[ndx]); }
情况2:目标列表存储自定义TempListGrappling2类型元素
如果TempListGrappling2是独立类,需要将Grappling2的属性映射过去:
// 假设TempListGrappling2类定义 public class TempListGrappling2 { public string ImageT { get; set; } public string TrainingText { get; set; } } // 初始化原列表 Grappling2 = new List<Grappling2> { new Grappling2 { ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png", TrainingText = "Iron Gate" }, new Grappling2 { ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png", TrainingText = "Long guard" } }; // 初始化目标列表 TempListGrappling2 = new List<TempListGrappling2>(); var rand = new Random(); // 生成6个元素的随机列表 for (int counter = 0; counter < 6; counter++) { int ndx = rand.Next(Grappling2.Count); var sourceItem = Grappling2[ndx]; // 创建TempListGrappling2实例并赋值属性 TempListGrappling2.Add(new TempListGrappling2 { ImageT = sourceItem.ImageT, TrainingText = sourceItem.TrainingText }); }
关键修改点
- 修正目标列表的类型匹配问题,确保添加的元素类型与列表泛型一致
- 随机索引范围限定为原列表的有效索引(
0到Grappling2.Count - 1),避免索引越界异常 - 直接添加原列表的元素(或映射后的自定义类实例),而非错误地创建数组
内容的提问来源于stack exchange,提问作者LotanV
相关产品推荐
相关产品推荐

