[英]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()
方法返回一個新的List
,因此將HashSet
轉換為List
應該保證List
對象中值的唯一性。
顯示以下內容的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 StackOverflow
{
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.