© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
18 replies
Shadow Wizard Money Gang

✅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.
    [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);
    }
    [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);
    }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Return groups of results using LINQ?
C#CC# / help
4y ago
❔ Shuffling Table Values
C#CC# / help
3y ago
❔ Put results of LINQ query into collection
C#CC# / help
3y ago
Get max index using linq
C#CC# / help
3y ago