[英]How can I implement a C# shuffle algorithm in an extension method?
我有一个看起来像这样的列表:
IList<TQBase> hs;
public class TQBase
{
public int i { get; set; }
public int q { get; set; }
}
我想打乱这个列表,发现了这个方法:
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
我正在尝试像这样使用它:
IList<TQBase> tqhb // This is populated from the repository in an earlier statement
var abc = tqhb.Shuffle<TQBase>();
它给我一个错误,指向abc并说:
Cannot assign void to an implicitly-typed local variable
我尝试洗牌的方式是否有问题?
一种很简单的洗牌方式:
hs.OrderBy(a => Guid.NewGuid()).ToList();
出于简单的混洗目的, Guid
足够随机。 为每个条目和顺序创建一个Guid
,它将最终以随机列表的形式出现。
我知道它不能解决您扩展程序中的问题,但是其他人已经解决了它。 似乎您在寻找一种改组机制,而不是特别在寻找一种改组机制,因此我提供了一种易于使用的替代方法。
您正在尝试在扩展方法返回类型void
时为新变量分配值。 像这样使用它:
tqhb.Shuffle<TQBase>();
扩展方法可以内联随机播放列表,您不必将返回值分配给任何内容(因此,返回类型为何为void
!)。
tqhb.Shuffle<TQBase>();
另外,编译器应该足够聪明以找出方法的通用类型,因此您应该能够调用
tqhb.Shuffle();
您的扩展方法存在错误:
public static IList<T> Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
或者,您无需分配即可使用它:
tqhb.Shuffle<TQBase>();
tqhb之后将有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.