0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# で in 句 : The "IN" operator in C#

Posted at

はじめに

ネットで、C# in句 で検索すると、以下のものが見つかります。
しかし満足できなかったので自分用のスニペットを作成しました。

サンプルコード

サンプルコードを見ていただければ一目瞭然ですが、Contains() があれば別に In() など要らない気がします。

まあ、でも可読性のために欲しくなるケースもあるでしょう。

using System;
using System.Linq;

namespace InTest
{
    static class Ext
    {
        public static bool In<T>(this T source, params T[] list)
        {
            return list.Contains(source);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            if (5.In(1, 2, 3, 4, 5)) Console.WriteLine("Match!");

            var productName = "Macbook Air";
            var appleProducts = new string[] { "Macbook Air", "Macbook Pro", "Mac mini", "iMac" };

            if (productName.In(appleProducts)) Console.WriteLine("Match!");
        }
    }
}

// #error version -> コンパイラ バージョン: '3.7.0-6.20371.12 (917b9dfa)'。言語バージョン: default。
// いや、default ってなんや。

正規表現版

正規表現と組み合わせると、存在意義が少し向上するような気がします。

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace InByRegexTest
{
    static class Ext
    {
        public static bool In(this string source, params string[] patterns)
        {
            return patterns.Any(pattern => Regex.IsMatch(source, pattern));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string productName = "Macbook Air";
            string[] appleProductPatterns = new string[] {
                "[m|M]ac.*",
                "iPhone[0-9]*",
                "Apple TV [4K|HD]",
            };

            if (productName.In(appleProductPatterns)) Console.WriteLine("Match!");
            if ("iPhone12".In(appleProductPatterns)) Console.WriteLine("Match!");
            if ("Apple TV 4K".In(appleProductPatterns)) Console.WriteLine("Match!");
        }
    }
}
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?