我如何为每个循环编写下面的linq查询 [英] How do i write linq query for below for each loop

查看:90
本文介绍了我如何为每个循环编写下面的linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表< GlobalFieldDatabase> fin =  new  List< GlobalFieldDatabase>(); 
foreach var t in bg){
if (UserEntites.ContainsKey(t.BudgetEntityCode)){
if (UserGlobalFields.ContainsKey(t.GlobalFieldCode))
{
GlobalFieldDatabase g = new GlobalFieldDatabase();
g.BudgetEntityId = UserEntites [t.BudgetEntityCode];
g.GlobalFieldId = UserGlobalFields [t.GlobalFieldCode];
g.GlobalFieldValue = t.GlobalFieldValue;
fin.Add(g);
}
}
}





我尝试了什么:



我试过但无法完成浪费大量时间的任务TIA

解决方案

这是可能的当然,但它在清晰度或代码节省方面没有太大的帮助(而且它也不会更快,因为LINQ本身并不比传统方法更快):

< pre lang =c#>列表< GlobalFieldDatabase> fin =
来自 t in bg
where UserEntites.ContainsKey(t.BudgetEntityCode)
&& UserGlobalFields.ContainsKey(t.GlobalFieldCode)
select new GlobalFieldDatabase()
{
BudgetEntityId = UserEntites [t.BudgetEntityCode],
GlobalFieldId = UserGlobalFields [t.GlobalFieldCode],
GlobalFieldValue = t.GlobalFieldValue
})
.ToList();





编辑:按以上保留我并不是说我会建议不要在这里使用LINQ,只是没有客观的好处,你必须根据个人喜好自行决定使用哪种方法。


List<GlobalFieldDatabase> fin = new List<GlobalFieldDatabase>();
          foreach(var t in bg){
                 if(UserEntites.ContainsKey(t.BudgetEntityCode)){
                     if (UserGlobalFields.ContainsKey(t.GlobalFieldCode))
                     {
                         GlobalFieldDatabase g = new GlobalFieldDatabase();
                         g.BudgetEntityId = UserEntites[t.BudgetEntityCode];
                         g.GlobalFieldId = UserGlobalFields[t.GlobalFieldCode];
                         g.GlobalFieldValue = t.GlobalFieldValue;
                         fin.Add(g);
                     }
                 }
                 }



What I have tried:

I have tried but couldn't accomplish the task wasted lots of time TIA

解决方案

It's possible of course but it doesn't gain you much in terms of clarity or lines of code savings (and it also isn't faster, as LINQ isn't inherently faster than a conventional approach):

List<GlobalFieldDatabase> fin =
    (from t in bg
     where UserEntites.ContainsKey(t.BudgetEntityCode)
     && UserGlobalFields.ContainsKey(t.GlobalFieldCode)
     select new GlobalFieldDatabase()
     {
         BudgetEntityId = UserEntites[t.BudgetEntityCode],
         GlobalFieldId = UserGlobalFields[t.GlobalFieldCode],
         GlobalFieldValue = t.GlobalFieldValue
     })
    .ToList();



Edit: By the above reservations I don't mean that I would advise against using LINQ here, just that there is no objective benefit and you'd have to decide yourself which approach to use based on personal preference.


这篇关于我如何为每个循环编写下面的linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆