有没有办法使用Shuffle()在List中随机检索SINGLE RECORD? - C#

时间:2016-04-08 03:25:57

标签: c# random

找到此Post,并且在List<T>中随机播放内容时,它有很好的解决方案。

但在我的情况下,我有一个类Person,其定义如下:

class Person
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Position { get; set; }
}

这是我的实施和用法:

List<Person> workers = new List<Person>()
{
    new Person { Id = 1, Name = "Emp 1", Position = "Cashier"},
    new Person { Id = 2, Name = "Emp 2", Position = "Sales Clerk"},
    new Person { Id = 3, Name = "Emp 3", Position = "Cashier"},
    new Person { Id = 4, Name = "Emp 4", Position = "Sales Clerk"},
    new Person { Id = 5, Name = "Emp 5", Position = "Sales Clerk"},
    new Person { Id = 6, Name = "Emp 6", Position = "Cashier"},
    new Person { Id = 7, Name = "Emp 7", Position = "Sales Clerk"}
};

现在我想要洗牌并获得1名销售员。这是我的代码并且正在运行:

var worker = workers.OrderBy(x => Guid.NewGuid()).Where(x => x.Position == "Sales Clerk").First();

// This can yield 1 of this random result (Emp 2, Emp 4, Emp 5 and Emp 7).
Console.WriteLine(worker.Name); 

但是根据给定的Post GUID对随机化记录不利。最糟糕的是我无法使用Shuffle()并调用WhereFirst()扩展程序来获得所需的结果。

如何使用Shuffle()扩展程序执行此操作?

2 个答案:

答案 0 :(得分:3)

如果问题是如何得到它所以你可以将Shuffle()链接到其余的Linq运算符,答案是修改Shuffle方法以返回对shuffled列表的引用:

public static IEnumerable<T> Shuffle<T>(this IList<T> list)
{
    RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
    int n = list.Count;
    while (n > 1)
    {
        byte[] box = new byte[1];
        do provider.GetBytes(box);
        while (!(box[0] < n * (Byte.MaxValue / n)));
        int k = (box[0] % n);
        n--;
        T value = list[k];
        list[k] = list[n];
        list[n] = value;
    }

    return list;
}

然后您的代码变为:

var worker = workers.Shuffle().Where(x => x.Position == "Sales Clerk").First();

答案 1 :(得分:1)

public boolean validate()
{
   boolean ret;
   // write your own validation logic
   if (validation logic is true)
   {
       ret = true;
   }

  return ret;

}