Increase Code Performance

How to get rid of foreach and get the same result. How can I improve the performance of my code by getting rid of the foreach loop.

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

      

+3


source to share


4 answers


Try this: -

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

      



Instead of selecting, anonymous type

you can directly fill in your own type.

+8


source


Let LINQ create objects tblcourse

instead of anonymous objects.



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

      

+4


source


I would boil it down to something like:

Note. I removed the unused variables. I also assumed that testEntities1 is an Entity Framework DbContext and needs to be disposed of. I also used the result variable to temporarily hold the link to the list so that it can be easily debugged by adding a breakpoint.

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

      

Of course, replacing foreach

with an operator LINQ

probably won't improve performance, but it will probably be more maintainable now.

You really want to take a look at the C # guide on best practices for naming class members.

+4


source


If you mean how to make it look cleaner (since the performance gain is sloppy), you can do it like this:

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

      

+1


source







All Articles