问题描述
我有如下IEnumerable集合
I have got an IEnumerable collection as follows
var result1 = GetResult1() // Returns 2,4,5,6
我必须弄乱元素并以随机方式创建另一个集合,其结果如下:
I have to juggle the elements and create another collection in a random way which should result as follows:
var result2 = GetResult2(result1) // Returns 2,4,5,6 in a random order.
// An example output would be 4,6,2,5 in the resultant collection.
我通过以下方式完成此操作:
I have done this by the following means:
var result1 = GetResult1();
var random = new Random();
var result2 = result1.OrderBy(order=>random.Next());
但是,问题是,如果我访问result2,则result2中的元素会再次洗牌,即我将result2的结果输出到控制台两次,元素又变了。
However the issue with this is that if I access result2 the elements in result2 gets shuffled again, i.e if I output the results of result2 to a console twice, the elements are juggled again.
请问如何保持这种统一性。也就是说,一旦我处理完收藏之后,之后应该保持相同的状态。不过,我必须使用惰性评估,因为结果的规模非常大。
Can you please advice how to keep this uniform. i.e once I juggle the collection, it should remain the same way thereafter. I have to use lazy evaluation though, since the results are very huge in size.
推荐答案
我看到您需要对惰性评估结果,如果是这样,您可以执行以下操作:
I see you require lazy evaluation for the results, if that is the case, what you can do is this:
var randomNumbers = result1.Select(r => random.Next()).ToArray();
var orderedResult = result1.Zip(randomNumbers, (r, o) => new { Result = r, Order = o })
.OrderBy(o => o.Order)
.Select(o => o.Result);
通过随机调用 ToArray()
数字,这些不会改变。当您最终希望得到 result
中的项目时,可以使用随机数压缩项目, OrderBy
随机数和选择
结果。
By calling ToArray()
on the random numbers, these will not change. When you finally desire the items in result
, you can zip the items with the random numbers, OrderBy
the random number and Select
the result.
只要结果
中的项目以相同顺序出现,则结果为每次的orderedResult
应该相同。
As long as the items in result
come in the same order, the result in orderedResult
should be the same each time.
这篇关于IEnumerable的随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!