bpe*_*aro 2 c# extension-methods
我正在使用一个扩展通用列表的扩展方法.这有效
public static void 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建另一个使用Shuffle()的扩展方法,但是会根据定义的组大小将组中的项目分组.调试扩展方法时,此方法似乎有效,但调用代码中的源列表仍包含扩展调用后的原始列表:
public static void GroupRandomize<T>(this IList<T> sourceList, int groupSize)
{
List<T> shuffledList = new List<T>();
List<T> tempList = new List<T>();
int addCounter = 0;
for (int i = 0; i < sourceList.Count; i++)
{
tempList.Add(sourceList[i]);
// if we've built a full group, or we're done processing the entire list
if ((addCounter == groupSize - 1) || (i == sourceList.Count - 1))
{
tempList.Shuffle();
shuffledList.AddRange(tempList);
tempList.Clear();
addCounter = 0;
}
else
{
addCounter++;
}
}
sourceList = shuffledList;
}
Run Code Online (Sandbox Code Playgroud)
如何确保洗牌列表正确存储到源列表中?
sourceList实际上是一个局部变量.可能会更好return shuffedList;
var newList = caller.GroupRandomize<T>(5) ;
Run Code Online (Sandbox Code Playgroud)