如何在扩展方法中实现C#shuffle算法?
我有一个如下列表:如何在扩展方法中实现C#shuffle算法?,c#,C#,我有一个如下列表: IList<TQBase> hs; public class TQBase { public int i { get; set; } public int q { get; set; } } IList<TQBase> tqhb // This is populated from the repository in an earlier statement var abc = tqhb.Shuffle<TQBase>
IList<TQBase> hs;
public class TQBase
{
public int i { get; set; }
public int q { get; set; }
}
IList<TQBase> tqhb // This is populated from the repository in an earlier statement
var abc = tqhb.Shuffle<TQBase>();
tqhb.Shuffle<TQBase>();
我尝试洗牌的方式有问题吗?一种非常简单的洗牌方式:
hs.OrderBy(a => Guid.NewGuid()).ToList();
对于简单的洗牌目的,Guid
是随机的。为每个条目创建一个Guid
,并按其排序,它最终将成为一个无序列表
我意识到它不能解决扩展中的问题,但其他人已经涵盖了它。您似乎在寻找一种洗牌机制,而不是这个机制,因此我提供了一种易于使用的替代方法。一种非常简单的洗牌方法:
hs.OrderBy(a => Guid.NewGuid()).ToList();
对于简单的洗牌目的,Guid
是随机的。为每个条目创建一个Guid
,并按其排序,它最终将成为一个无序列表
我意识到它不能解决扩展中的问题,但其他人已经涵盖了它。似乎您正在寻找一种洗牌机制,而不是这个机制,因此我提供了一种易于使用的替代方法。当扩展方法返回type
void
时,您正在尝试为一个新变量赋值。像这样使用它:
IList<TQBase> hs;
public class TQBase
{
public int i { get; set; }
public int q { get; set; }
}
IList<TQBase> tqhb // This is populated from the repository in an earlier statement
var abc = tqhb.Shuffle<TQBase>();
tqhb.Shuffle<TQBase>();
tqhb.Shuffle();
当扩展方法返回typevoid
时,您正试图为新变量赋值。像这样使用它:
IList<TQBase> hs;
public class TQBase
{
public int i { get; set; }
public int q { get; set; }
}
IList<TQBase> tqhb // This is populated from the repository in an earlier statement
var abc = tqhb.Shuffle<TQBase>();
tqhb.Shuffle<TQBase>();
tqhb.Shuffle();
扩展方法内联地洗牌列表,您不必为任何内容分配返回值(因此返回类型为void
!)
扩展方法以内联方式洗牌列表,您不必为任何内容分配返回值(因此返回类型为
void
!)
扩展方法中存在错误:
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;
}
公共静态IList Shuffle(此IList列表)
{
随机rng=新随机();
int n=list.Count;
而(n>1){
n--;
int k=下一个(n+1);
T值=列表[k];
列表[k]=列表[n];
列表[n]=值;
}
退货清单;
}
或者,您使用它时没有分配:
tqhb.Shuffle<TQBase>();
tqhb.Shuffle();
tqhb之后将不同。您的扩展方法中有一个错误:
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;
}
公共静态IList Shuffle(此IList列表)
{
随机rng=新随机();
int n=list.Count;
而(n>1){
n--;
int k=下一个(n+1);
T值=列表[k];
列表[k]=列表[n];
列表[n]=值;
}
退货清单;
}
或者,您使用它时没有分配:
tqhb.Shuffle<TQBase>();
tqhb.Shuffle();
tqhb之后将不同。var abc=tqhb.Shuffle()代码>洗牌();返回void.var abc=tqhb.Shuffle()代码>洗牌();返回void。