如果不存在于不同的列表中,则仅将随机数放入列表中

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 是否已经存在于被比较的列表中并且无法弄清楚语法。

再多一只眼睛就好了。

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

可以 添加一个 else 子句,并且只将它添加到 HashSet 中,如果它还没有在那里,但是 Add 方法执行此操作(即 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();

由于 HashSet.ToList() 方法 returns 一个新的 List,将 HashSet 转换为 List 应该可以保证 List 中值的唯一性=15=]对象。

ToList 方法的源代码显示如下:

public static List<TSource> ToList<TSource> (this IEnumerable<TSource> source)
{
    Check.Source (source);
    return new List<TSource> (source);
}

在您的应用中,您只需要自己的临时变量来存储您要检查的随机数。下面的示例程序显示了两种实现方式。

#define UNCONDITIONAL

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


namespace Whosebug
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            HashSet<int> hash = new HashSet<int>();
            Random rnd = new Random();

#if(UNCONDITIONAL)
            Console.WriteLine("Adding unconditionally...");
#else
            Console.WriteLine("Adding after checks...");
#endif

            while(hash.Count < 5)
            {
                int rv = rnd.Next (1, 11);
#if(UNCONDITIONAL)
                hash.Add (rv);
#else
                if(hash.Contains(rv))
                {
                    Console.WriteLine ("Duplicate skipped");
                }
                else
                {
                    hash.Add (rv);
                }
#endif
            }

            List<int> list = hash.ToList ();  // ToList() gives back a new instance
            foreach(var e in list)
            {
                Console.WriteLine (e);
            }
        }
    }
}

注意: UNCONDITIONAL 符号只是为了让您更轻松地尝试示例。您可以将其注释掉以查看这两种行为。

定义了符号的示例输出:

Adding unconditionally...
5
10
2
6
3

注释掉符号的示例输出:

Adding after checks...
Duplicate skipped
7
3
4
2
10