LoginSignup
6
7

More than 5 years have passed since last update.

複数のプロパティを配列化する

Posted at

例えば

    public class HoGE
    {
        public bool Param1 { get; set; }
        public bool Param2 { get; set; }
        public bool Param3 { get; set; }
        public bool Param4 { get; set; }
        public bool Param5 { get; set; }
        public bool Param6 { get; set; }
        public bool Param7 { get; set; }
        public bool Param8 { get; set; }
        public bool Param9 { get; set; }
        public bool Param10 { get; set; }
    }

こんなクラスがあったとして
このクラスのboolがtrueのプロパティ名を配列化したいみたいなパターン。

    var hoge = new HoGE
            {
                Param1 = true,
                Param5 = true,
                Param9 = true,
            };

を処理して
[ "Param1" , "Param5", "Param9"]
ってしたい感じで取得したい時。

ゴリゴリ書けば

string[] h = Enumerable.Range(1, 10)
                    .Select(x =>
                    {
                        switch (x)
                        {
                            case 1: return hoge.Param1 ? nameof(hoge.Param1) : "";
                            case 2: return hoge.Param2 ? nameof(hoge.Param2) : "";
                            case 3: return hoge.Param3 ? nameof(hoge.Param3) : "";
                            case 4: return hoge.Param4 ? nameof(hoge.Param4) : "";
                            case 5: return hoge.Param5 ? nameof(hoge.Param5) : "";
                            case 6: return hoge.Param6 ? nameof(hoge.Param6) : "";
                            case 7: return hoge.Param7 ? nameof(hoge.Param7) : "";
                            case 8: return hoge.Param8 ? nameof(hoge.Param8) : "";
                            case 9: return hoge.Param9 ? nameof(hoge.Param9) : "";
                            case 10: return hoge.Param10 ? nameof(hoge.Param10) : "";
                            default: return "";
                        }
                    }).Where(x => x != "").ToArray();

こんな感じかな。

PropertyInfoとか使えば


string[] h = properties
                    .Where(pi => pi.Name.StartsWith("Param") && (bool)pi.GetValue(hoge))
                    .Select(pi => pi.Name)
                    .ToArray();

こんな感じ。

もっと良い書き方あるような気がするんだけど、思いつかない。

6
7
1

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
6
7