tags:

views:

63

answers:

2

I have a LINQ query to a DataTable:

var list = from row in table.AsEnumerable()
group row by row.Field<byte>("ID") into g
select new
{
   ID = g.Key,
   Name = (from c in g
      select c.Field<string>("name")).First(),
   Localized = (from c in g
      select myDic[c.Field<string>("name"))].First();
};

where ID is a primary column, Name - data from query and Localized - a value from a dictionary where key - that data from query (Name).

Will LINQ cache that data from query for the second select or I have to do this in another way?

And another question: if I'll put dictionary creation in select, will it been crated every time?

+1  A: 

LINQ does not cache data. Therefore, it will perform the dictionary lookup for every element of every group.

itowlson
+2  A: 

LINQ does not do any kind of query analysis/optimizations (see note below). Instead use the C# "let" clause (which maps to the SelectMany method) to capture that value once for reuse in the select statement. Here is your revised query:

var list = from row in table.AsEnumerable()
group row by row.Field<byte>("ID") into g
let name = (from c in g
            select c.Field<string>("name")).First()
select new
{   
    ID = g.Key,   
    Name = name,
    Localized = myDic[name]
};

NOTE: IQueryable providers can technically translate LINQ expressions into more optimal ones if they wanted to, but that's a subject of another discussion and you're using pure "LINQ to Objects" here anyway.

Drew Marsh