Search code examples
c#asp.netmodularity

How to remove repeating code in this method?


private static Game[] getMostPlayedGamesDo(int Fetch, int CategoryID)
{
    Game[] r;
    using (MainContext db = new MainContext())
    {
        if (CategoryID == 0)
        {
            var q = db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch);
            r = new Game[q.Count()];
            int i = 0;
            foreach (var g in q)
            {
                r[i] = new Game(g);
                i++;
            }
        }
        else
        {
            var q = db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch);
            r = new Game[q.Count()];
            int i = 0;
            foreach (var g in q)
            {
                r[i] = new Game(g);
                i++;
            }
        }
    }
    return r;
}

I can't seem to define q outside the scope of the if, and I can't insert the returned values to the array outside the scope of the if! Not sure how to remove repeating code in this simple instance?


Solution

  • It's not clear what the type of q is -- but deducing from your usage:

    db.tblArcadeGames.OrderByDescending(...)
    

    Presumably it's an entity class from Linq-To-Sql or Entity Framework. In that case, you do have a concrete entity defined, presumably named tblArcadeGame. Therefore, move q out of the scope by not using var:

    IQueryable<tblArcadeGame> q;
    if (CategoryID == 0)
    {
        q = db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch);
    }
    else
    {
        q = db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch);
    }
    r = new Game[q.Count()];
    int i = 0;
    foreach (var g in q)
    {
        r[i] = new Game(g);
        i++;
    }
    

    As you can see, the repeated code is now seen only once.

    P.S. Tools like ReSharper are fantastic for this sort of thing. Using it, with one keystroke you can toggle between the var version and that using explicitly named types.