问题描述:

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 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.

网友答案:

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++;
}
网友答案:

I assume q is type IQueryable.

private static Game[] getMostPlayedGamesDo(int Fetch, int CategoryID)
{
    var q = db.tblArcadeGames;
    if (CategoryID != 0)
    {
        q = q.Where(c => c.CategoryID == CategoryID);
    }
    q = q.OrderByDescending(c => c.Plays).Take(Fetch);
    return q.Select(g => new Game(g)).ToArray();
}
网友答案:
    List<tblArcadeGame> q;
    /* object q; */


    if (CategoryID == 0)
    {
        q = db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch).ToList();
    }
    else
    {
        q = db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch).ToList();
    }

        r = new Game[q.Count()];
        int i = 0;
        foreach (var g in q)
        {
            r[i] = new Game(g);
            i++;
        }

I'll assume q is List<tblArcadeGame>

相关阅读:
Top