[英]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.