2017-09-06 11 views
0

上記の例のようなプロパティで製品を見つけるには、どのような方法がありますか?私は、3000個の製品のリストを持っています。それぞれの製品は、例のように12個のプロパティーオブジェクトのリストを持っています。 n個のプロパティを使用して素早く製品を見つけることができる必要があります。T1 []でT1を見つける効率的な方法T2 []ここで、T2 []はT1のプロパティですか?

public class Test 
{ 
    public class ProductProperty 
    { 
     public string Name { get; set; } 
     public string Value { get; set; } 
     public ProductProperty() { } 
     public ProductProperty(string name, string value) 
     { 
      this.Name = name; 
      this.Value = value; 
     } 
    } 
    public class Product 
    { 
     public string ProductName { get; set; } 
     public ProductProperty[] Properties { get; set; } 
    } 

    public static void Main(string[] args) 
    { 
     List<Product> models = new List<Product>() 
     { 
      new Product() { ProductName = "Test1", Properties = new ProductProperty[] { new ProductProperty("title", "car"), new ProductProperty("length", "5") } }, 
      new Product() { ProductName = "Test1", Properties = new ProductProperty[] { new ProductProperty("title", "car"), new ProductProperty("length", "7") } }, 
      new Product() { ProductName = "Test1", Properties = new ProductProperty[] { new ProductProperty("title", "ship"), new ProductProperty("length", "9") } }, 
     }; 

     var findByProps = new ProductProperty[] { new ProductProperty("title", "car"), new ProductProperty("length", "7") }; 

     // var product = find Product that has title=car and length=7 

    } 
} 

答えて

4

あなたはProductProperty内部Equalsメソッドをオーバーライドする場合:

public override bool Equals(object o) => o is ProductProperty p && p.Name == Name && p.Value== Value; 

それは(あなたもIEquatableを実装することができます)お互いにProductPropertyを比較する方が簡単です。 (NB、上記の構文は、古いビジュアルスタジオではサポートされていないが、必要に応じて簡単に書き換えることができる) 一度上書き入っていて、任意のデフォルトの方法は、使用することができます。

var product = models.FirstOrDefault(m=> findByProps.All(m.Properties.Contains)); 
+1

を、それが一度だけのアクション 'である場合FirstOrDefault'が動作します。それを何度もやりたいのであれば、あなたのコレクションをソートし、バイナリ検索を使うことをお勧めします。 – rraszewski

+0

それは面白いです! "m => findByProps.All(m.Properties.Contains)"について詳しく説明します。?Containsには何がパラメータとして渡されますか? findByPropsの各要素は? "m => findByProps.All(prop => m.Properties.Contains(prop))"と書くのと同じですか? –

+1

はい、それは同じですが、余分なラムダはありません。 Properties配列インスタンスの 'Contains'メソッドは、' All'(拡張)メソッドに直接渡されるので、 'All'内部の各繰り返しで直接呼び出すことができます –

関連する問題