Pregunta

Sugiera una forma más fácil de obtener una colección aleatoria aleatoria de count 'n' de una colección que tiene elementos 'N'. donde n < = N

¿Fue útil?

Solución

Otra opción es usar OrderBy y ordenar por un valor GUID, que puede hacerlo usando:

var result = sequence.OrderBy(elem => Guid.NewGuid());

Hice algunas pruebas empíricas para convencerme de que lo anterior en realidad genera una distribución aleatoria (que parece hacer). Puede ver mis resultados en Técnicas para reordenar una matriz aleatoriamente .

Otros consejos

Además de la respuesta de mquander y el comentario de Dan Blanchard, aquí hay un método de extensión compatible con LINQ que realiza un Shuffle Fisher-Yates-Durstenfeld :

// take n random items from yourCollection
var randomItems = yourCollection.Shuffle().Take(n);

// ...

public static class EnumerableExtensions
{
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.Shuffle(new Random());
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (rng == null) throw new ArgumentNullException("rng");

        return source.ShuffleIterator(rng);
    }

    private static IEnumerable<T> ShuffleIterator<T>(
        this IEnumerable<T> source, Random rng)
    {
        var buffer = source.ToList();
        for (int i = 0; i < buffer.Count; i++)
        {
            int j = rng.Next(i, buffer.Count);
            yield return buffer[j];

            buffer[j] = buffer[i];
        }
    }
}

Esto tiene algunos problemas con " sesgo aleatorio " y estoy seguro de que no es óptimo, esta es otra posibilidad:

var r = new Random();
l.OrderBy(x => r.NextDouble()).Take(n);

Mezcle la colección en un orden aleatorio y tome la primera < code> n elementos del resultado.

Un poco menos aleatorio, pero eficiente:

var rnd = new Random();
var toSkip = list.Count()-n;

if (toSkip > 0)
    toSkip = rnd.Next(toSkip);
else
    toSkip=0;

var randomlySelectedSequence = list.Skip(toSkip).Take(n);

Escribo este método de anulación:

public static IEnumerable<T> Randomize<T>(this IEnumerable<T> items) where T : class
{
     int max = items.Count();
     var secuencia = Enumerable.Range(1, max).OrderBy(n => n * n * (new Random()).Next());

     return ListOrder<T>(items, secuencia.ToArray());
}

private static IEnumerable<T> ListOrder<T>(IEnumerable<T> items, int[] secuencia) where T : class
        {
            List<T> newList = new List<T>();
            int count = 0;
            foreach (var seed in count > 0 ? secuencia.Skip(1) : secuencia.Skip(0))
            {
                newList.Add(items.ElementAt(seed - 1));
                count++;
            }
            return newList.AsEnumerable<T>();
        }

Entonces, tengo mi lista de fuentes (todos los elementos)

var listSource = p.Session.QueryOver<Listado>(() => pl)
                        .Where(...);

Finalmente, llamo " Aleatorizar " y obtengo una subcolección aleatoria de artículos, en mi caso, 5 artículos:

var SubCollection = Randomize(listSource.List()).Take(5).ToList();

Perdón por el código feo :-), pero


var result =yourCollection.OrderBy(p => (p.GetHashCode().ToString() + Guid.NewGuid().ToString()).GetHashCode()).Take(n);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top