2017-09-06 1 views
0

주어진 예제와 같은 속성을 사용하여 제품을 빠르게 찾을 수있는 방법은 무엇입니까? 나는 3000 개의 제품 목록을 가지고 있는데, 각 제품은 예제에서와 같이 12 개의 속성 개체 목록을 가지고 있습니다. n 개의 속성을 사용하여 신속하게 제품을 찾을 수 있어야합니다.T2 []에 의해 T1 []에서 T1을 찾는 효율적인 방법 여기서 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 메서드를 오버라이드 (override)하는 경우 :

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

이 (당신은 또한 IEquatable을 구현할 수) 서로 ProductProperty을 비교하는 것이 더 쉽습니다.

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

을 단지 한 번 작업 인 경우': 포함 등 (NB는, 위의 구문은 나이가 비주얼 스튜디오에서 지원되지 않지만, 필요한 경우 쉽게 다시 작성할 수 있습니다) 는 일단 무시, 어떤 기본 방법을 사용할 수 있습니다 FirstOrDefault'가 효과적입니다. 여러 번 해보고 싶다면 컬렉션을 정렬하고 이진 검색을 사용하는 것이 좋습니다. – rraszewski

+0

그건 재미 있어요! "m => findByProps.All (m.Properties.Contains)"에 대해 자세히 설명합니다.? Contains로 전달되는 매개 변수는 무엇입니까? findByProps의 각 요소는 무엇입니까? "m => findByProps.All (prop => m.Properties.Contains (prop))"라고 쓰는 것과 같은가요? –

+1

네, 동일하지만 여분의 람다는 없습니다. Properties 배열 인스턴스의'Contains' 메쏘드는'All' (확장) 메쏘드에 직접 전달되므로'All' 안의 각각의 반복문에 의해 직접 호출 될 수 있습니다 –

관련 문제