Random Query List Linq to Entity C # [duplicate]

1

I would like to get a list of 3 objects within a query Link.

var listaPessoas = from i in this.Context.CreateObjectSet<listaPessoas>()
        select i;
...
listaPessoas  = listaPessoas .Where(x => x.Nome.Contains(filtro.Nome);
...
return listaPessoas;

However, in this return I would like to get only 3 objects (always random) inside elements in listaPessoas

    
asked by anonymous 31.08.2017 / 15:28

2 answers

4

Use a Random object to sort the list and Take method to limit the amount of items returned.

Random rnd = new Random();
listaPessoas = listaPessoas.OrderBy(p => rnd.Next()).Take(3).ToList();

See working in .NET Fiddle.

As you want to do this in the bank, you will need something different. One way to do this is to sort by Guid , since it is not possible to know what is going to be generated, the ordering will be random.

listaPessoas.OrderBy(r => Guid.NewGuid()).Take(3).ToList();

This option is great because it does not significantly increase the size of query and its complexity.

    
31.08.2017 / 15:41
3

Best way to use it is Fisher-Yates shuffle (algorithm to generate a random permutation of a finite sequence)

Create an extension:

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)
    {
        List<T> 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];
        }
    }
}

way to use:

listaPessoas = listaPessoas.Shuffle().Take(3);
    
31.08.2017 / 15:47