我有一个列表,我按照这样的分数订购:
var orderedList = outcomeRequestModels
.Where(m => m.Score > 0)
.OrderByDescending(m => m.Score).ToList();
我想做的是,将列表中的项目随机分配得分相同。 所以,如果我有这样的项目列表:
var t = [{
name: 'test 1',
score: 20
}, {
name: 'test 2',
score: 30
}, {
name: 'test 3',
score: 20
}, {
name: 'test 4',
score: 20
}, {
name: 'test 5',
score: 20
}, {
name: 'test 6',
score: 30
}, {
name: 'test 7',
score: 15
}, {
name: 'test 8',
score: 20
}, {
name: 'test 9',
score: 30
}];
我希望这样订购:
var t = [{
name: 'test 9',
score: 30
}, {
name: 'test 6',
score: 30
}, {
name: 'test 2',
score: 30
}, {
name: 'test 1',
score: 20
}, {
name: 'test 4',
score: 20
}, {
name: 'test 5',
score: 20
}, {
name: 'test 3',
score: 20
}, {
name: 'test 8',
score: 20
}, {
name: 'test 7',
score: 15
}];
如果我再次通过,它会按顺序切换顺序:
var t = [{
name: 'test 6',
score: 30
}, {
name: 'test 2',
score: 30
}, {
name: 'test 9',
score: 30
}, {
name: 'test 8',
score: 20
}, {
name: 'test 4',
score: 20
}, {
name: 'test 5',
score: 20
}, {
name: 'test 1',
score: 20
}, {
name: 'test 3',
score: 20
}, {
name: 'test 7',
score: 15
}];
有谁知道我该怎么做?
答案 0 :(得分:2)
您可以通过任意分配的唯一值“打破”来随机化:
var orderedList = outcomeRequestModels
.Select(m => new {Model = m, RandomId = Guid.NewGuid()})
.Where(m => m.Model.Score > 0)
.OrderByDescending(m => m.Model.Score)
.ThenBy(m => m.RandomId)
.Select(m => m.Model)
.ToList();
当然,这并不是真正的随意,但会给人一种非常好的外表。同样的方法可以与Random
的实例一起使用,但没有太大的改变:
var rnd = new Random();
var orderedList = outcomeRequestModels
.Select(m => new { Model = m, RandomId = rnd.Next() })
.Where(m => m.Model.Score > 0)
.OrderByDescending(m => m.Model.Score)
.ThenBy(m => m.RandomId)
.Select(m => m.Model)
.ToList();
答案 1 :(得分:0)
被殴打 - 但另一个答案略有不同,以帮助ORM评论。
像
这样的东西var rnd = new Random();
var orderedList = models
.Where(m => m.Score > 0)
.AsEnumerable() // Optional - This should alleviate the ORM comment in the previous answer
.Select(m => new { m.Name, m.Score, Rand = rnd.Next() })
.OrderByDescending(m => m.Score).ThenBy(m => m.Rand)
.Select(m => new { m.Name, m.Score }) // Optional
.ToList();