Random list in Query Linq to Entity C#

Asked

Viewed 317 times

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 pick up only 3 objects (always random) within the elements in listaPessoas

2 answers

4


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

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

See working on . NET Fiddle.

As you want to do this in the bank, you will need something different. One way to do it is to sort by a Guid, as it is not possible to know what will 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 the query nor the complexity of it.

  • in my project I get this error. " LINQ to Entities does not recognize the method 'Int32 Next()' method, and this method cannot be Translated into a store Expression."

  • @Brunoheringer You should have said you are using Entity Framework. You want to do this randomization in the database or in memory?

  • Could be in the bank.

  • @Brunoheringer I gave an option

  • Good @Link. Top. Vlw

3

Best way to use is with 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 of using:

listaPessoas = listaPessoas.Shuffle().Take(3);
  • Because it’s the best way?

  • Because it’s an algorithm designed to do that, scramble a finite sequence.

  • And what makes it the best way to do it? What is the basis for this statement?

  • Just read on the link I put, there already makes the comparison of this to the other algorithms. Search the page for "Comparison with other Shuffling Algorithms"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.