将foreach循环转换为LINQ请求 [英] Convert foreach loop to LINQ request

查看:123
本文介绍了将foreach循环转换为LINQ请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在LINQ中编写以下代码



谢谢,



列表与LT;类型> selectedList = new List< Type>(); 
foreach(allTypes中的类型类型)
{
if(type!= null)
{
if(type.BaseType!= null)
{
if(type.BaseType.Name ==MyBASETYPE)
{
inheritedList.Add(type);
}
}
}
}





我尝试了什么:



我写了这个,但似乎它不起作用,因为在某些情况下,baseType为null



 var selectedList = allTypes.Where(p => p.BaseType.Name ==MyBASETYPE)。选择(p => new {p}); 

解决方案

在您的示例中,不确定您对 inheritedList 的期望。除此之外,我相信你正在寻找以下(完全等同):



 var selectedList = allTypes 
。 Where(type => type!= null&& type.BaseType!= null&&
type.BaseType.Name ==MyBASETYPE)
.ToList();


而不是试图无缘无故地使用LINQ(如果你认为它会更好地再次思考,LINQ通常会更慢),你会更好地改进您对基础知识的理解。



列表<类型> selectedList = new List< Type>(); 
foreach(类型类型为allTypes)
{
if(type!= null&& type.BaseType!= null&& type.BaseType.Name ==MyBASETYPE )
{
inheritedList.Add(type);
}
}





如其他解决方案中所述,根据您的.net版本,您也可以使用?。


I'm trying to write the code below in LINQ

Thank you,

List<Type> selectedList = new List<Type>();
foreach (Type type in allTypes)
{
  if (type != null)
  {
      if (type.BaseType != null)
      {
         if (type.BaseType.Name == "MyBASETYPE")
         {
            inheritedList.Add(type);
         }
      }
   }
}



What I have tried:

I wrote this but it seems it's not working because for some case, the baseType is null

var selectedList = allTypes.Where(p => p.BaseType.Name == "MyBASETYPE").Select(p => new { p });

解决方案

Not certain what you expect from inheritedList in your example. Other than that, I believe you are looking for the following (to be fully equivalent):

var selectedList = allTypes
  .Where(type => type != null && type.BaseType != null &&
    type.BaseType.Name == "MyBASETYPE")
  .ToList();


Rather than trying to use LINQ for no reason (if you think it is going to perform better think again, LINQ is often slower), you'd be better improving your understanding of the basics.

List<Type> selectedList = new List<Type>();
foreach (Type type in allTypes)
{
  if (type != null && type.BaseType != null && type.BaseType.Name == "MyBASETYPE")
  {
      inheritedList.Add(type);
   }
}



As mentioned in the other solution depending on your version of .net you can also use "?."


这篇关于将foreach循环转换为LINQ请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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