2011-05-05 3 views

답변

4

이 서로 다른을 DistrictId와 ContactId의 조합으로 사용하려면 GroupBy을 사용할 수 있으므로 중복을 어떻게 처리할지 결정하십시오. 이 경우 각 그룹은 하나의 별개의 조합으로 분류되는 항목을 나타냅니다.

var results = context.MyCollection 
        .GroupBy(x=> new { x.DistrictId, x.ContactId }) 
        .Select(...) 
+1

으로'Tuple.Create (x.DistrictId, x.ContactId)'를 사용하십시오. 각 그룹 중 하나가'Select (g => g.First() ;' – BrokenGlass

1

DistinctBy 메서드를 직접 작성하거나 시퀀스 유형을 유지하면서 시퀀스 내용의 예상 정보를 구별 할 수 있어야합니다.

MoreLINQan implementation of this method을 제공합니다.

+1

... 키 선택기 – Nappy

0

이 경우 처리 할 수있는 익명 형식을 만들 수 있습니다. 우리는에 DistinctBy 작업을 할 수있는 확장 메서드를 정의 할 수 있습니다

IList<Element> element = new List<Element>(); 


      var result = new { P1 = element 
           .Select(X => X.FirstProp).Distinct() 
          , 
           P2 = element 
            .Select(X => X.SecondProp).Distinct() 
          , 
           element 
           // do projections here over others 8 properties 


      }; 
0

: 10 개 속성 클래스를 가정 하는 요소

public class Element 
    { 
     public int FirstProp { get; set; } 
     public int SecondProp { get; set; } 

     //others 8 cool properties 
    } 

LINQ에서 확장 방법으로 당신이 원하는 추출하는 쿼리입니다 다음과 같은 T의 숫자는 다음과 같습니다.

public static class EnumerableExtensions 
     { 

      /// <summary> 
      /// Returns a ienumerable which is distinct by a given property key selector. If a custom equality 
      /// comparer is to be used, pass this in as the comparer. By setting the comparer default to null, 
      /// the default comparer is used. 
      /// </summary> 
      /// <typeparam name="T">The item type in the ienumerable</typeparam> 
      /// <typeparam name="TKey">The type of the key selector (property to disinct elements by)</typeparam> 
      /// <param name="coll">The source ienumerable</param> 
      /// <param name="keySelector">The key selector, use a member expression in a lambda expression</param> 
      /// <param name="comparer">Custom comparer to use, pass in null here to specify that default comparer is used, 
      /// however, this is default set to null and not required parameter</param> 
      /// <returns></returns> 
      public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> coll, Func<T, TKey> keySelector, 
       IEqualityComparer<TKey> comparer = null) 
      { 
       if (coll == null) 
        throw new ArgumentNullException("coll"); 
       if (keySelector == null) 
        throw new ArgumentNullException("keySelector"); 

       var result = coll.GroupBy(keySelector, comparer).Select(g => g.First()).ToList(); 
       return new List<T>(result).AsEnumerable(); 
      } 

     } 

DistinctBy 연산자는 예를 들어 간단한 콘솔 응용 프로그램에서 테스트 할 수 있습니다. 우리는 색깔 조합 모델 +의 한 자동차를 원하는 즉 별개의 (모델, 컬러) 튜플을 얻을 :

클래스 프로그램 {

static void Main(string[] args) 
    { 

     var cars = new [] 
     { 
      new Car {Model = "Audi", Make = "A4", Color = "Black"}, 
      new Car {Model = "Audi", Make = "A8", Color = "Red"}, 
      new Car {Model = "Audi", Make = "TT", Color = "Black"}, 
      new Car {Model = "Volvo", Make = "XC90", Color = "Black"}, 
      new Car {Model = "Volvo", Make = "S90", Color = "Black"}, 
      new Car {Model = "Ferrari", Make = "F500", Color = "Yellow"}, 
      new Car {Model = "Ferrari", Make = "F500", Color = "Red"}, 
      new Car {Model = "Lada", Make = "Limousine", Color = "Rusty"} 
     }; 

     var groupedCars = cars.DistinctBy(c => new {c.Model, c.Color}); 


     foreach (var gc in groupedCars) 
     { 
      Console.WriteLine(gc.ToString()); 
     } 

     Console.WriteLine("Press any key to continue ..."); 
     Console.ReadKey(); 
    } 




    // Define other methods and classes here 

} 

출력은 다음과 같습니다

Model: Audi, Make: A4, Color: Black 
Model: Audi, Make: A8, Color: Red 
Model: Volvo, Make: XC90, Color: Black 
Model: Ferrari, Make: F500, Color: Yellow 
Model: Ferrari, Make: F500, Color: Red 
Model: Lada, Make: Limousine, Color: Rusty 
Press any key to continue ... 

우리 우리가 이미 검은 Audi를 가지고 있기 때문에 항목 "Audi TT Black"을 얻지 못했습니다. 우리는 이미 "Volvo S90 Black"을 얻지 못했습니다. 왜냐하면 우리는 이미 검은 볼보를 가지고 있기 때문입니다. 두 색의 페라리 F500이 있습니다. 그리고 슬프게도, 모델과 컬러의 유일한 조합 이었기 때문에 우리는 "Lada Limousine Rusty"에 매달 렸습니다.

관련 문제