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?
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:
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.