我有一个类的对象列表Author,我想根据作者的一个属性搜索这个作者列表name,当我收到一个匹配项时,我想返回Author用于创建实例的实例另一个类,它需要Author作为其构造函数的一部分.
解释它的更好方法是:
author getAuthor(String arg_name)
{
foreach (author auth in authorList)
{
if (auth.name == arg_name)
{
return auth;
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我意识到这个特定代码确实有效,但是有更好的方法来执行此操作吗?
您可以使用Enumerable.FirstOrDefault:
return authorList.FirstOrDefault(a=> a.name == arg_name);
Run Code Online (Sandbox Code Playgroud)
null如果任何具有名称的作者与传递的参数不匹配,则会返回.
对于您的特定代码,您的检查if (auth == arg_name)应该给您编译时错误.你的支票应该是if (auth.name == arg_name)