假设我有这样一条if语句:
if (a > x || b > x || c > x || d > x) {}
假设它总是涉及相同的重复变量(在本例中是x)和相同的操作,但操作在所有使用之间并不相同。例如,另一个if语句可以使用:
if (x.Contains(a) || x.Contains(b) || x.Contains(c) || x.Contains(d)) {}
有没有一种方法可以在C#中简化这些if语句,这样我们就不会一遍又一遍地输入相同的东西?我不希望为这个实例调用额外的函数。
发布于 2013-03-12 16:18:42
你可以使用LINQ,但如果你只有四个条件,它就不太有用了:
if (new[] {a,b,c,d}.Any(current => current > x))
和
if (new[] {a,b,c,d}.Any(current => x.Contains(current)))
发布于 2013-03-12 16:19:55
发布于 2013-03-12 16:34:45
没有什么能阻止你做你自己的扩展,让事情变得更清晰;
public static class LinqExtension
{
public static bool ContainsAny<TInput>(this IEnumerable<TInput> @this, IList<TInput> items)
{
return @this.Any(items.Contains);
}
}
https://stackoverflow.com/questions/15366458
复制