2

これは具体的な質問ではなく、長い間頭に浮かんだ一般的な質問です。

文字列のリストからの値が含まれているかどうかを1つの変数で確認する必要があります

例えば

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

SQLでは、この種のステートメントを書くのは非常に簡単です。

ステータスが( "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))

Anyメソッドの代わりにContainメソッドを使用することもできますが、実装する比較ロジックがある場合は、デフォルトの等式比較プログラムの代わりに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");

これは、このような多くのステートメントを作成する必要がある場合に最適です。少なくとも5〜10個のステートメントステートメントの古いスタイルを2つ以上のファイルで作成する場合は、この拡張機能を作成することをお勧めします。

于 2012-04-09T10:42:20.950 に答える