使用 C#/Asp.Net。
我正在努力实现以下目标:
我有一个报价单 - 有时有多个产品的价格相同。
此外,一些结果是附属的(赞助),因此我们也需要优先考虑这些结果。
这是被调用的方法:
public IEnumerable<PriceQuote> BestQuote(int take = 0)
{
var q = Quotes.Where(x => x.TotalRepayable == MinPrice)
.Shuffle()
.OrderByDescending(x => x.ProductDetail.Product.IsSponsored);
return take == 0 ? q : q.Take(take);
}
该代码选择可用价格最低的商品。然后,我们的想法是将它们按完全随机的顺序排序,然后再次按赞助标志降序排序(赞助 = 1 而不是 0),然后取所需的任意结果。
我首先将它们洗牌以获得随机顺序 - 从随机列表中我想先拿赞助项目 - 然后如果需要用非赞助项目填充空间。理论上,赞助和非赞助每次都会以随机顺序排列。
Example in natural order:
product1 (not sponsored)
product2 (sponsored)
product3 (not sponsored)
product4 (sponsored)
product5 (not sponsored)
product6 (sponsored)
Shuffle randomly:
product3 (not sponsored)
product1 (not sponsored)
product2 (sponsored)
product6 (sponsored)
product5 (not sponsored)
product4 (sponsored)
Order by sponsored first keeping randomness:
product2 (sponsored) <-- pick these first
product6 (sponsored)
product4 (sponsored)
product3 (not sponsored)
product1 (not sponsored)
product5 (not sponsored)
这是我的随机播放方法:
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> @this)
{
if (@this.Count() <= 1) return @this;
return @this.ShuffleIterator(new Random());
}
static IEnumerable<T> ShuffleIterator<T>(this IEnumerable<T> source, Random rng)
{
var buffer = source.ToList();
for (int i = 0; i < buffer.Count; i++)
{
int j = rng.Next(i, buffer.Count);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
我遇到的问题是,当我针对不同的报价连续多次调用 BestQuote 方法时,我往往会返回相同的结果。例如,我的列表包含 6 种产品,我进行了 3 次调用,每次都选择第一个结果,很可能所有 3 次调用的顺序都相同。情况并非总是如此 - 存在一些差异,但匹配项多于非匹配项。
Call 1: product2 <--
Call 2: product2 <--
Call 3: product2 <-- this is a common scenario where there seems to be no randomness
最佳答案
试试这个:
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> @this)
{
if (@this.Count() <= 1) return @this;
Random rand = new Random();
return @this.Select(x => new { x = x, r = rand.Next() }).OrderBy(x => x.r).Select(x => x.x);
}
关于c# - 试图获得随机排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41696666/