score:8

Accepted answer

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 your custom Type.

score:4

Let LINQ create the tblcourse objects 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();
}

score:1

If you mean how do you get it to look cleaner (as the performance gain is negligable), you can do so 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();
}

score:4

I'd reduce it to something like:

Note: I've removed the unused variables. I've also assumed that testEntities1 is an Entity Framework DbContext and requires disposing. I've also used the results variable to temporarily hold a reference to the list so 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 the foreach with a LINQ statement probably wont improve performance much, but it's probably more maintainable now.

You really want to look at a guide for best practices of naming class members in C#.


Related Articles