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:

  1. some name
  2. some other name
  3. something else

then next time, be:

  1. some other name
  2. some name
  3. 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

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -