[英]How to use a method with an out parameter in a lambda expression
I have a method which looks the following way: 我有一种方法,它看起来如下:
bool GetIdByName(string name, out ID id)
I would like to use it inside a lambda expression, to get several 'ids' by a number of 'names': 我想在lambda表达式中使用它,以通过多个“名称”获取多个“ id”:
var ids = names.Select(name => idService.GetIdByName(name, out id));
In this case I will find all the bool values inside my 'ids' variable, which is not what I want. 在这种情况下,我会在“ ids”变量中找到所有布尔值,这不是我想要的。 Is it also possible to get the out parameter 'id' of each call into it?
是否还可以将每个调用的out参数'id'插入其中?
You can use a delegate with body for this: 您可以使用带有body的委托:
IEnumerable<ID> ids = names.Select
(
name =>
{
ID id;
GetName(name, out id);
return id;
}
);
I would factor the call to GetIdByName
into a method, so that it becomes more composable. 我会将对
GetIdByName
的调用GetIdByName
为一个方法,以使其变得更加可组合。
var ids = names.Select(GetId);
private static ID GetId(string name)
{
ID id;
idService.GetIdByName(name, out id);
return id;
}
Are looking for something like that? 是否正在寻找类似的东西?
var ids = names
.Select(name => {
ID id = null;
if (!idService.GetIdByName(name, out id))
id = null; // name doesn't corresponds to any ID
return id;
})
.Where(id => id != null);
In case ID
is a struct (and so not nullable ): 如果
ID
是一个结构 (因此不能为null ):
var ids = names
.Select(name => {
ID id = null;
Boolean found = idService.GetIdByName(name, out id);
return new {
Found = found,
ID = id
};
})
.Where(data => data.Found)
.Select(data => data.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.