Select items from ASP.NET collections as a percentage

I have a collection including 100 copies.

Collection<int> myCollection = new Collection<int>();

for(int i; i <= 100; i++)
{
    myCollection .Add(i);
}

How can I randomly select percentages (e.g. 30%) from this collection?

+4
source share
2 answers

Try the following:

var rand = new Random();
var top30percent = myCollection.OrderBy(x=> rand.Next(myCollection.Count))
                               .Take((int)(0.3f*myCollection.Count)).ToList();

You can delete ToList()if you want to postpone the request.

+4
source

There are two parts to your question. First, you must shuffle your collection to randomly select items. To shuffle it, you can do it right with Shuffle Fisher-Yates or just order your goods using a pseudo-random generator.

Fisher-Yates :

public static IList<T> Shuffle<T>(this IList<T> list)  
{  
    Random rng = new Random();  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  

    return list;
}

, , . , , OrderBy i => random.Next() i => Guid.NewGuid() -.

-, , . Take LINQ.

Shuffle, :

public static IEnumerable<int> TakePercentage(this IList<int> list, int percentage)
{
    return list.Take(percentage * list.Count / 100);
} 

(, 0,3) :

public static IEnumerable<int> TakePercentage(this IList<int> list, double percentage)
{
    return list.Take((int)(percentage * list.Count));
} 

, , :

var thirtyPercent = myCollection.Shuffle().Take(30);
+2

All Articles