如何删除此方法中的重复代码?

时间:2011-11-19 04:44:19

标签: c# asp.net modularity

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;
}

我似乎无法在q的范围之外定义if,并且我无法将返回的值插入到if范围之外的数组中!不确定如何在这个简单的实例中删除重复代码?

4 个答案:

答案 0 :(得分:4)

目前尚不清楚q的类型是什么 - 而是从您的使用中推断出来:

db.tblArcadeGames.OrderByDescending(...)

据推测,它是来自Linq-To-Sql或Entity Framework的实体类。在这种情况下,您定义了一个具体的实体,大概名为tblArcadeGame。因此,请不要使用q

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++;
}

正如您所看到的,现在只能看到重复的代码一次。

P.S。像ReSharper这样的工具对于这类事情非常棒。使用它,通过一次击键,您可以在var版本和使用明确命名的类型之间切换。

答案 1 :(得分:1)

你应该只是明确地输入q。但这可能会让你在没有它的情况下逃脱(三元运营商会为你强制执行)。

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++;
}

答案 2 :(得分:1)

我假设q是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();
}

答案 3 :(得分:0)

    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++;
        }

我认为qList<tblArcadeGame>