使用c#从id集合中获取4个(或任何计数)随机唯一ID的最简单方法是什么?

Bar*_*Alp 1 c# asp.net generics c#-3.0

假设你有一个idCollection IList<long>并且你有一个方法来获得4个唯一的id.每次调用它时,它会为你提供随机的4个唯一ID?

var idCollec = new[] {1,2,3,4,5,6,7,8,9,10,11,12}.ToList();

For example {2,6,11,12}
            {3,4,7,8}
            {5,8,10,12}
            ...
            ..
Run Code Online (Sandbox Code Playgroud)

最聪明的方法是什么?

谢谢

Dav*_*vy8 5

似乎最简单的方法是拥有类似的东西:

if(idCollection.Count <4)
{
    throw new ArgumentException("Source array not long enough");
}
List<long> FourUniqueIds = new List<long>(4);
while(FourUniqueIds.Count <4)
{
    long temp = idCollection[random.Next(idCollection.Count)];
    if(!FourUniqueIds.Contains(temp))
    {
        FourUniqueIds.add(temp);
    }
}
Run Code Online (Sandbox Code Playgroud)