2016-09-02 1 views
1

"場所"を変更すると、手動で各プロパティ名を追加するのではなく、文字列を含むすべてのプロパティを自動的にチェックしますか?文字列であるすべてのプロパティを検索

items.Where(m => m.Property1.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           || m.Property2.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           || m.Property3.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           || m.Property4?.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           || m.Property5?.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           || m.Property6.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           || m.Property7?.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0 
           )); 

ありがとうございます。

+3

あなたは* *反射を使用しようとしたことがありますか? –

+2

'm.GetType()。GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.ReturnType == typeof(string))' – Casey

答えて

1

私はリフレクションを使用してコードを書くでしょう...

public bool MyContains(object instance, string word) 
{ 
     return instance.GetType() 
       .GetProperties() 
       .Where(x => x.PropertyType == typeof(string)) 
       .Select(x => (string)x.GetValue(instance, null)) 
       .Where(x => x != null) 
       .Any(x => x.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0); 
} 

次に、あなたのコードはLBの回答に基づいて

items.Where(m=>MyContains(m,word)); 
0

次のようになります。私は

彼の答えを受け入れ私は2つの機能に分解した。 ストライその場所の各インスタンスのプロパティ。

public static class ObjectUtils 
{ 
    public static IEnumerable<PropertyInfo> GetPropertiesByType<TEntity>(TEntity entity, Type type) 
     { 
      return entity.GetType().GetProperties().Where(p => p.PropertyType == type); 
     } 

    public static bool CheckAllStringProperties<TEntity>(TEntity instance, IEnumerable<PropertyInfo> stringProperties, string word) 
     { 
      return stringProperties.Select(x => (string)x.GetValue(instance, null)) 
       .Where(x => x != null) 
       .Any(x => x.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0); 
     } 
} 

その後

var stringProperties = ObjectUtils.GetPropertiesByType(new Item(), typeof(string)); 

items.Where(x => ObjectUtils.CheckAllStringProperties(x, stringProperties, word))); 
関連する問題