开发者

WIll LINQ cache a value if a select for it presents twice?

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 fr开发者_运维问答om 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:

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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜