简体   繁体   English

如何在扩展方法中实现C#随机播放算法?

[英]How can I implement a C# shuffle algorithm in an extension method?

I have a list that looks like this: 我有一个看起来像这样的列表:

IList<TQBase> hs;

public class TQBase
{
    public int i { get; set; }
    public int q { get; set; }
}

I would like to shuffle this list and I found this method: 我想打乱这个列表,发现了这个方法:

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;  
    }  
}

I am trying to use it like this: 我正在尝试像这样使用它:

 IList<TQBase> tqhb // This is populated from the repository in an earlier statement

 var abc = tqhb.Shuffle<TQBase>();

It's giving me an error pointing to abc and saying: 它给我一个错误,指向abc并说:

 Cannot assign void to an implicitly-typed local variable   

Is there a problem with the way I am trying to do the shuffle ? 我尝试洗牌的方式是否有问题?

A very easy way to shuffle: 一种很简单的洗牌方式:

hs.OrderBy(a => Guid.NewGuid()).ToList();

For simple shuffling purposes a Guid is random enough. 出于简单的混洗目的, Guid足够随机。 Create a Guid for each entry and order by it, it will end up as a shuffled list. 为每个条目和顺序创建一个Guid ,它将最终以随机列表的形式出现。

I realize it doesn't solve the problem in your extension, but others have already covered it. 我知道它不能解决您扩展程序中的问题,但是其他人已经解决了它。 It seems like you were looking for a shuffle mechanism and not this one in particular so I provided an easy-to-use alternative. 似乎您在寻找一种改组机制,而不是特别在寻找一种改组机制,因此我提供了一种易于使用的替代方法。

You are trying to assign a new variable a value when your extension method returns type void . 您正在尝试在扩展方法返回类型void时为新变量分配值。 Use it like this: 像这样使用它:

tqhb.Shuffle<TQBase>();

The extension method shuffles the list inline, you don't have to assign the return to anything (Hence why the return type is void !). 扩展方法可以内联随机播放列表,您不必将返回值分配给任何内容(因此,返回类型为何为void !)。

tqhb.Shuffle<TQBase>();

Also, the compiler should be smart enough to figure out the generic type of the method so you should just be able to call 另外,编译器应该足够聪明以找出方法的通用类型,因此您应该能够调用

tqhb.Shuffle();

There's an error in your Extension method: 您的扩展方法存在错误:

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; 
}

Or, you use it without assignment: 或者,您无需分配即可使用它:

tqhb.Shuffle<TQBase>();

After tqhb will be different. tqhb之后将有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM