RPM1984
RPM1984

Reputation: 73132

C# Generic List<T> - How to Randomly Assign a "Rank" To Each Item?

So i have the following generic list:

var topTenSomething = new List<Something>();

Here is Something:

public class Something
{
   public string Name { get; set; }
   public int Rank { get; set; }
}

So i want to randomly assign the "Rank" property, but it needs to be ordered from 1-number of items in the collection.

So if the collection has 3 items, i want to randomly assign ranks from 1 to 3:

  1. Some Name
  2. Some Other Name
  3. Something Else

Then next time, it could be:

  1. Some Other Name
  2. Some Name
  3. Something Else

Know what i mean?

Not sure how to do it - any ideas?

This is for a simple R&D prototype - so don't worry about performance/why i am doing this. (the real one will have rank assigned by database)

Happy with either a LINQ/non-LINQ version - as long as it works.

Upvotes: 1

Views: 1161

Answers (2)

Adam Spicer
Adam Spicer

Reputation: 2721

This should work:

List<Something> somethings = new List<Something>();

/* TODO: populate list here... */

Random rand = new Random();
somethings.ForEach(s=>s.Rank = rand.Next(1, somethings.Count - 1));

Upvotes: 0

SLaks
SLaks

Reputation: 887479

Like this:

var rand = new Random();
var sequence = Enumerable.Range(0, list.Count).OrderBy(i => rand.Next()).ToList();

for(var i = 0; i < list.Count; i++)
    list[i].Rank = sequence[i];

If you want the list to be sorted by the random rank:

var rand = new Random();
list.Sort((a, b) => rand.Next(-1, 2));    //Exclusive upper bound
for(var i = 0; i < list.Count; i++)
    list[i].Rank = i;

However, this is not a valid ordering (a < b does not imply b > a) and may cause unexpected results.

Upvotes: 5

Related Questions