我有另一个名为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();更多推荐
发布评论