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?
It’s not clear what the type of
qis — but deducing from your usage: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, moveqout of the scope by not usingvar: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
varversion and that using explicitly named types.