개체 집합이 있고 컬렉션에서 DISTINCT를 수행하려고합니다. 반환 된 객체에는 각각 약 10 개의 속성이 있습니다. 프로퍼티를 사용하여 정말 투영 할 수있는 옵션이 필요합니다. 10 가지 속성 중 하나만 DISTINCT를 두 개의 필드 (DistrictId 및 ContactId)에 적용해야합니다. 어떻게해야합니까?LINQ (.NET 4)를 사용하여 DISTINCT 쿼리를 수행하려면 어떻게합니까?
답변
이 서로 다른을 DistrictId와 ContactId의 조합으로 사용하려면 GroupBy
을 사용할 수 있으므로 중복을 어떻게 처리할지 결정하십시오. 이 경우 각 그룹은 하나의 별개의 조합으로 분류되는 항목을 나타냅니다.
var results = context.MyCollection
.GroupBy(x=> new { x.DistrictId, x.ContactId })
.Select(...)
DistinctBy
메서드를 직접 작성하거나 시퀀스 유형을 유지하면서 시퀀스 내용의 예상 정보를 구별 할 수 있어야합니다.
MoreLINQ은 an implementation of this method을 제공합니다.
... 키 선택기 – Nappy
이 경우 처리 할 수있는 익명 형식을 만들 수 있습니다. 우리는에 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
};
: 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"에 매달 렸습니다.
- 1. 테이블에 존재하지 않는 조건에서이 LINQ 쿼리를 수행하려면 어떻게합니까?
- 2. Linq 쿼리를 사용하여 구별
- 3. LINQ 쿼리를 수행하고 선택하려면 어떻게합니까?
- 4. 날짜별로 LINQ 쿼리를 필터링하려면 어떻게합니까?
- 5. .NET Framework 4를 사용하는 동적 LINQ API
- 6. Linq-To-Sql, MVC, Distinct 쿼리를 사용한 열거 가능한 결과
- 7. DISTINCT 행을 합계하려면 어떻게합니까?
- 8. 엔티티에 Linq : 유니온 + Distinct
- 9. LINQ Distinct 및 IEquality
- 10. LINQ Distinct Query
- 11. SDL을 사용하여 키 반복을 동시에 수행하려면 어떻게합니까?
- 12. .NET 4를 사용하여 작업 파이프 라인 만들기?
- 13. C# LINQ Distinct (IEqualityComparer) help
- 14. LINQ 쿼리를 사용하여 데이터 그룹화
- 15. LINQ 쿼리를 사용하여 Descents 열거
- 16. LINQ 쿼리를 사용하여 이미지 표시
- 17. 피들러 JScript.NET 함수에서 PInvoke를 수행하려면 어떻게합니까?
- 18. 플래시 클라이언트로 세션을 수행하려면 어떻게합니까?
- 19. .NET 4.0의 Entity Framework에서 "와"와일드 카드 비교를 수행하려면 어떻게합니까?
- 20. linq 쿼리를
- 21. SQL에서이 쿼리에서 피벗을 수행하려면 어떻게합니까?
- 22. EF 쿼리에서 날짜 비교를 수행하려면 어떻게합니까?
- 23. Linux 커널에서 표준 라이브러리 호출을 수행하려면 어떻게합니까?
- 24. 두 개의 COUNT/DISTINCT 쿼리를 최적화하십시오.
- 25. NHibernate - COUNT (DISTINCT)를 사용하는 Linq 질의
- 26. 설치 프로젝트에서 .NET 4를 두 번 설치하려고합니다.
- 27. LINQ 쿼리를 한 열로 좁히기
- 28. 레일즈 "찾기"메소드를 사용하여 AND 또는 OR 쿼리를 수행하려면 어떻게해야합니까?
- 29. LINQ-to_XML 쿼리를 사용하여 XML을 검색하는 방법
- 30. LINQ. 동적 쿼리를 사용하여 코드 줄이기
으로'Tuple.Create (x.DistrictId, x.ContactId)'를 사용하십시오. 각 그룹 중 하나가'Select (g => g.First() ;' – BrokenGlass