c# 中是否有任何比较运算符,例如 SQL 的 IN 语句
本文关键字:SQL 例如 IN 语句 运算符 是否 任何 比较 | 更新日期: 2023-09-27 18:30:40
这不是一个具体的问题,而是一个长期存在于我脑海中的通用问题
我必须检查一个变量是否包含字符串列表中的值
例如
status == "Open" || status =="Active" || status =="Reopen" || status = "InActive" etc..
在SQL中,编写这种语句非常容易,例如
从状态为("打开"、"活动"、"重新打开"、"非活动")的工单中选择 *。
我想知道我们在 C# 中没有这么简单的语句?
有没有人知道像SQL这样的简单方法来编写这种语句,而无需使用ifelse,foreach循环或LINQ等泛型类型。
我知道 LINQ 在那里,但它仍然不像 sql 的 IN 那么简单
tickets.Where(t => new[] {"Open",
"Active",
"Reopen",
"InActive"}.Any(x => x == t.status))
还可以使用 Contain(包含)方法而不是 Any 方法,但如果要实现任何比较逻辑,请使用 Any 方法,而不是默认相等比较器。
或
实现扩展以支持 IN 方法:
public static class Extensions
{
public static bool In<TItem>(this TItem source, Func<TItem, TItem, bool> comparer, IEnumerable<TItem> items)
{
return items.Any(item => comparer(source, item));
}
public static bool In<TItem, T>(this TItem source, Func<TItem, T> selector, IEnumerable<TItem> items)
{
return items.Select(selector).Contains(selector(source));
}
public static bool In<T>(this T source, IEnumerable<T> items)
{
return items.Contains(source);
}
public static bool In<TItem>(this TItem source, Func<TItem, TItem, bool> comparer, params TItem[] items)
{
return source.In(comparer, (IEnumerable<TItem>)items);
}
public static bool In<TItem, T>(this TItem source, Func<TItem, T> selector, params TItem[] items)
{
return source.In(selector, (IEnumerable<TItem>)items);
}
public static bool In<T>(this T source, params T[] items)
{
return source.In((IEnumerable<T>)items);
}
}
并像这样使用:
bool b;
b = 7.In(3, 5, 6, 7, 8); // true
b = "hi".In("", "10", "hi", "Hello"); // true
b = "hi".In("", "10", "Hi", "Hello"); // false
b = "hi".In((s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase), "", "10", "Hi"); // true
var tuples = new List<Tuple<int, string>>();
for (var i = 0; i < 10; i++)
{
tuples.Add(Tuple.Create(i, ""));
}
var tuple = Tuple.Create(3, "");
b = tuple.In(tup => tup.Item1, tuples); // true
(new [] { "Open", "Active", "Reopen", "InActive" }).Contains(status)
这对
我有用。
(new List<string>{ "Open", "Active", "Reopen", "InActive" }).Contains("status");
我也喜欢创建字符串类扩展的 c# 3.0 功能
public static class StringExtensions
{
public static bool In(this string @this, params string[] strings)
{
return strings.Contains(@this);
}
}
稍后我们可以以最简单的方式使用它
status.Contains("Open", "Active", "Reopen", "InActive");
如果您必须编写许多这样的语句,这很棒,如果我在 5 个或更多文件中为至少 5-10 个语句语句编写旧样式,我更喜欢编写此扩展。