Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 571
Tom Gullen Avatar asked Jun 27 '26 07:06

Tom Gullen


2 Answers

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.

like image 197
Kirk Woll Avatar answered Jun 29 '26 19:06

Kirk Woll


You should really just explicitly type q. But this may let you get away without it (ternary operator will enforce it for you).

var q = CategoryID == 0 ? db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch)
                        : 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++;
}
like image 35
Andy Avatar answered Jun 29 '26 20:06

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!