kelsier
kelsier

Reputation: 4100

Simplifying LINQ

public List<KeyValuePair<decimal, string>> getDepartments()
{
    using (DBEntities db = new DBEntities ())
    {
        var dept = (from i in db.Departments
                    orderby i.DepartmentName
                    select new
                    {
                        i.Id,
                        i.DepartmentName
                    }).ToDictionary(Key => Key.Id, Value => Value.DepartmentName);

        return dept.ToList<KeyValuePair<decimal, string>>();
    }
}

In the above function, I need a List<KeyValuePair<decimal, string>>. So I first convert IQueryable to Dictionary .ToDictionary(Key => Key.Id, Value => Value.DepartmentName) and then to List using .ToList<KeyValuePair<decimal, string>>();.

But it seems expensive. How do I reduce it? How do I avoid using too much conversions(like ToDictionary, ToList)?

UPDATE 1:

It was someone else's code, just figured why that .ToList is there after checking the response data in Chrome. When .ToList is used, the response data would look like 0: {Key:13, Value:Marketing} 1: {Key:5, Value:Research} which populates a dropdown and is angularjs-friendly. When I remove it and return it as a Dictionary the response data would look like {"13":"Marketing","5":"Research"} which fails to populate the dropdown. So I can't remove .ToList. Is there a way I can get a List<KeyValuePair<decimal, string>> from IQueryable without using ToDictionary?

Upvotes: 0

Views: 97

Answers (1)

Ronan Thibaudau
Ronan Thibaudau

Reputation: 3603

Only the first call (todictionary on iqueryable) is going to be expensive (database call), the 2nd one is done in memory and unless you're working on a huge huge dataset, it's gonna be pretty much free.

However i can't think of any reason "why" you'd want to convert from a dictionary to a list of keyvaluepairs since a dictionary is already an ienumerable of those keyvaluepairs.

So no it's not expensive but you're probably better of reworking the consuming code and just returning the dictionnary.

update after your comment : Try this and see if it shows the json you want :

public IEnumerable<KeyValuePair<decimal, string>> getDepartments()
{
    using (DBEntities db = new DBEntities ())
    {
        var dept = (from i in db.Departments
                    orderby i.DepartmentName
                    select new
                    {
                        i.Id,
                        i.DepartmentName
                    }).ToDictionary(Key => Key.Id, Value => Value.DepartmentName);
        foreach(var item in dept)
           yield return item;
    }
}

Upvotes: 4

Related Questions