✅Shuffling db results using LINQ.

Is there a way to shuffle db results using linq?
I've tried copying some code from online using .orderby(...) but it doesnt seem to work.

I have this code that returns all words from a db, shuffles them all then returns just the first x but it's horribly inefficient.
c#
    [HttpGet]
    public async Task<List<WordDto>> Get(string? categoryName)
    {
        var words = _db.Words.AsQueryable();

        if (categoryName is not null)
        {
            words = words
                .Where(w => w.Category.Name == categoryName);
        }
        
        var wordsList = await words
            .Select(w => new WordDto(w.Id, w.Text, w.Length, w.Category))
            .ToListAsync();
        
        //Shuffling all words in a category. Horribly ineffcient. 
        wordsList.Shuffle();
        //Return first x words.
        return wordsList.Slice(0, 3);
    }
Was this page helpful?