如果在不同的列表中不存在,则仅将随机数放入列表中(Only put random number in list if doesn't exist in a different list)

编程入门 行业动态 更新时间:2024-10-26 14:30:48
如果在不同的列表中不存在,则仅将随机数放入列表中(Only put random number in list if doesn't exist in a different list)

我有另一个名为lRVars列表

我正在尝试使用从循环生成的hashSet生成另一个列表,如下所示,但是,我需要确保该数字在上面的列表中不存在:

List<int> lCVars = new List<int>(); HashSet<int> hCVars = new HashSet<int>(); while (hCVars.Count < randCVarsCount) { hCVars.Add(rnd.Next(1, 11)); } lColVars = hsColVars.ToList();

所以在上面的循环中,我需要检查rnd.Next已经存在于被比较的列表中,并且无法弄清楚语法。

额外的眼睛会很棒。

I have another list named lRVars

I am trying to generate another list with a hashSet generated from a loop as follows, however, I need to make sure that the number doesn't already exist in the above list:

List<int> lCVars = new List<int>(); HashSet<int> hCVars = new HashSet<int>(); while (hCVars.Count < randCVarsCount) { hCVars.Add(rnd.Next(1, 11)); } lColVars = hsColVars.ToList();

So in the above loop, I need to check if the rnd.Next already exists in the list being compared and can't figure out the syntax.

An extra eye would be great.

最满意答案

您只需要一个随机数的临时变量,并使用它来检查它是否已存在。

可以添加一个else子句,只将其添加到HashSet如果它尚未存在),但Add方法hs.Add(8); hs.Add(8); //hs will only have count of 1即hs.Add(8); hs.Add(8); //hs will only have count of 1 )

List<int> lCVars = new List<int>(); HashSet<int> hCVars = new HashSet<int>(); var rnd = new Random(); var randCVarsCount = 5; while (hCVars.Count < randCVarsCount) { var num = rnd.Next(1, 11); if (hCVars.Contains(num)) Console.WriteLine("already in there"); hCVars.Add(num); } lColVars = hsColVars.ToList();

You just need a temporary variable for the random number and use that to check it already exists.

You could add an else clause and only add it to the HashSet if it isn't already in there, but the Add method does that (i.e. hs.Add(8); hs.Add(8); //hs will only have count of 1)

List<int> lCVars = new List<int>(); HashSet<int> hCVars = new HashSet<int>(); var rnd = new Random(); var randCVarsCount = 5; while (hCVars.Count < randCVarsCount) { var num = rnd.Next(1, 11); if (hCVars.Contains(num)) Console.WriteLine("already in there"); hCVars.Add(num); } lColVars = hsColVars.ToList();

更多推荐

本文发布于:2023-07-30 23:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340301.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   列表中   不存在   放入   则仅将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!