提高代码的性能

时间:2014-12-09 10:02:26

标签: c# linq entity-framework

如何摆脱foreach并仍然获得相同的输出。如何通过摆脱foreach循环来提高代码的性能。

public List<tblcourse> GetData(string value)
{
    testEntities1 db = new testEntities1();

    int v = Convert.ToInt32(value);
    testEntities1 t = new testEntities1();
    var u = (from g in t.tblcourses
             select new  { g.C_Id,  g.C_Name }).ToList();

    List<tblcourse> lisstt = new List<tblcourse>();

    foreach (var item in u)
    {
        tblcourse b = new tblcourse();
        b.C_Id = item.C_Id;
        b.C_Name = item.C_Name;
        lisstt.Add(b);
    }

    return lisstt;
}

4 个答案:

答案 0 :(得分:8)

试试这个: -

var u = (from g in t.tblcourses
             select new tblcourse { C_Id = g.C_Id, C_Name = g.C_Name }).ToList();

您可以直接填写自定义类型,而不是选择anonymous type

答案 1 :(得分:4)

让LINQ创建tblcourse个对象而不是匿名对象。

public List<tblcourse> GetData(string value)
{
    return (from g in db.tblcourses
            select new tblcourse() { C_Id = g.C_Id,  C_Name = g.C_Name }).ToList();
}

答案 2 :(得分:4)

我会把它缩小为:

注意:我删除了未使用的变量。我还假设testEntities1是一个Entity Framework DbContext并需要处理。我还使用结果变量暂时保存对列表的引用,以便通过添加断点轻松调试它。

public IList<tblcourse> GetData()
{
    using (var testContext = new testEntities1())
    {
        var results =
            testContext.tblcourses
                .Select(c => new tblcourse() { C_Id = c.C_Id, C_Name = c.C_Name })
                .ToList();

        return results;
    }
}

当然,用foreach语句替换LINQ可能不会提高性能,但现在可能更容易维护。

您真的想查看有关在C#中命名类成员的最佳做法的指南。

答案 3 :(得分:1)

如果你的意思是如何让它看起来更干净(因为性能增益可以忽略不计),你可以这样做:

public List<tblcourse> GetData(string value)
{
    return (from g in new testEntities1().tblcourses
             select new tblcourse { C_Id = g.C_Id, C_Name = g.C_Name }).ToList();
}