且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在linq中获得随机行,最后插入的行在顶部

更新时间:2023-12-03 15:34:46

好的,所以更新的要求是:

Okay, so the updated requirements are:

  • 获取所有项目
  • 除了第一个项目(它应该是最后一个添加的项目)之外,订购是随机的

首先,摆脱您的Skip通话.您没有在尝试跳过任何内容.只需将所有产品(可能已订购,请参见下文)放入列表中即可.

Firstly, get rid of your Skip call. You're not trying to skip anything. Just fetch all the products (possibly ordered - see below) into a list.

对于随机性部分,我会在调用代码中使用经过修改的Fischer-Yates随机播放来完成-在Stack Overflow上有很多示例,例如

For the randomness part, I'd do that in the calling code, using a modified Fischer-Yates shuffle - there are numerous examples of that on Stack Overflow, such as here.

在这种情况下,您可能希望将最新的项目移到列表的开头,然后将列表的 rest 随机排序.只需对改组的代码稍作修改,就很容易了-但是您需要首先将最新的项目移到列表的开头.您可以通过在LINQ查询中使用OrderByDescending(x => x.InsertionDate)(或其他任何方法)来执行此操作,或者仅获取所有内容并在内存行中的O(n)中找到最新行.使用OrderByDescending会更简单,但效率可能会稍低(因为您实际上并不需要完全订购).

In this case, you probably want to get the most recent item to the start of the list and then just shuffle the rest of the list. That's easy enough to do with a slight modification to the shuffling code - but you need to get the most recent item to the start of the list first. You could either do that by using OrderByDescending(x => x.InsertionDate) (or whatever) in your LINQ query, or just fetch everything and find the latest row in an O(n) pass over the rows in memory. Using OrderByDescending will be simpler, but potentially slightly less efficient (as you don't really need full ordering).