linq - C# Generic List<T> - How to Randomly Assign a "Rank" To Each Item? -
so have following generic list:
var toptensomething = new list<something>();
here something:
public class { public string name { get; set; } public int rank { get; set; } }
so want randomly assign "rank" property, needs ordered 1-number of items in collection.
so if collection has 3 items, want randomly assign ranks 1 3:
- some name
- some other name
- something else
then next time, be:
- some other name
- some name
- something else
know mean?
not sure how - ideas?
this simple r&d prototype - don't worry performance/why doing this. (the real 1 have rank assigned database)
happy either linq/non-linq version - long works.
like this:
var rand = new random(); var sequence = enumerable.range(0, list.count).orderby(i => rand.next()).tolist(); for(var = 0; < list.count; i++) list[i].rank = sequence[i];
if want list sorted random rank:
var rand = new random(); list.sort((a, b) => rand.next(-1, 2)); //exclusive upper bound for(var = 0; < list.count; i++) list[i].rank = i;
however, not valid ordering (a < b
not imply b > a
) , may cause unexpected results.
Comments
Post a Comment