[英]Select result of where clause
Take this method fe: 采取这种方法fe:
public static Function Parse(string codeAndData)
{
return (from factory in factories
where factory.Parse(codeAndData) != null
select factory.Parse(codeAndData)).FirstOrDefault();
}
As you can see, factory.Parse(codeAndData)
is called twice, which is bad practice. 如您所见,
factory.Parse(codeAndData)
被调用了两次,这是不好的做法。 Therefore we could write it like this: 因此我们可以这样写:
public static Function Parse(string codeAndData)
{
Function function = null;
return (from factory in factories
where (function = factory.Parse(codeAndData)) != null
select function).FirstOrDefault();
}
But the above doesn't seem very elegant to me. 但是以上对我来说似乎不是很优雅。 Is there a better LINQ alternative to this?
有没有更好的LINQ替代方案?
This is easy with the method chaining syntax: 使用方法链接语法很容易:
return factories.Select(f => f.Parse(codeAndData))
.FirstOrDefault(p => p != null);
With the comprehension syntax, you can accomplish this with let
: 使用comprehension语法,您可以使用
let
来实现:
return (from factory in factories
let p = factory.Parse(codeAndData)
where p != null
select p).FirstOrDefault();
Since you're already mixing FirstOrDefault with the comprehension syntax, you could also do this: 由于您已经将FirstOrDefault与Comprehension语法混合在一起,因此您也可以这样做:
return (from factory in factories
select factory.Parse(codeAndData))
.FirstOrDefault(p => p != null);
but that seems kind of a silly alternative to the first option. 但这似乎是第一种选择的愚蠢选择。
Instead of using assignments, you can do the selection procedure before: 除了使用分配,您还可以在执行选择过程之前:
public static Function Parse(string codeAndData) {
return (from factory in factories
select factory.Parse(codeAndData)
).Where(y => y != null).FirstOrDefault();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.