Reputation: 73132
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:
Then next time, it could be:
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
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
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