2

这不是一个具体的问题,而是一个笼统的问题,这是我长期以来一直在想的问题

我必须检查一个变量是否包含字符串列表中的值

例如

status == "Open" || status =="Active" || status =="Reopen" || status = "InActive" etc..

在 SQL 中,编写这种语句非常容易,例如

select * from ticket where status in ("Open","Active","Reopen","InActive)

我想知道我们在 C# 中没有这么简单的语句吗?

有谁知道像 SQL 这样的简单方法来编写这种语句而不使用 if else 、foreach 循环或 LINQ 等通用类型。

我知道 LINQ 在那里,但它仍然不像 sql 的 IN 那样简单

4

3 回答 3

8
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
于 2012-04-09T09:54:52.023 回答
7
(new [] { "Open", "Active", "Reopen", "InActive" }).Contains(status)
于 2012-04-09T09:56:14.290 回答
0

这对我有用。

(new List<string>{ "Open", "Active", "Reopen", "InActive" }).Contains("status");

我也喜欢为 String 类创建扩展的 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");

如果您必须编写许多这样的语句,这很好,如果我在 2 个或更多文件中为至少 5-10 个语句语句编写旧样式,我更喜欢编写此扩展名。

于 2012-04-09T10:42:20.950 回答