Domanda

Suggerisci un modo più semplice per ottenere una raccolta casuale mescolata di conteggio 'n' da una raccolta con elementi 'N'. dove n < = N

È stato utile?

Soluzione

Un'altra opzione è usare OrderBy e ordinare su un valore GUID, che puoi fare usando:

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

Ho fatto alcuni test empirici per convincermi che quanto sopra genera effettivamente una distribuzione casuale (che sembra fare). Puoi vedere i miei risultati su Tecniche per il riordino casuale di una matrice .

Altri suggerimenti

Oltre alla risposta di mquander e al commento di Dan Blanchard, ecco un metodo di estensione compatibile con LINQ che esegue 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];
        }
    }
}

Questo ha alcuni problemi con " bias casuale " e sono sicuro che non sia ottimale, questa è un'altra possibilità:

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

Shuffle la raccolta in un ordine casuale e prendere il primo < code> n dal risultato.

Un po 'meno casuale, ma efficiente:

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);

Scrivo questo metodo di sostituzione:

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>();
        }

Quindi, ho il mio elenco di fonti (tutti gli articoli)

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

Infine, chiamo " Randomize " e ricevo una sotto-raccolta casuale di articoli, nel mio caso, 5 articoli:

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

Ci scusiamo per il codice brutto :-), ma


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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top