2013-07-26 2 views
0

동일한 사용자 정의 유형의 목록이 2 개 있습니다. 각각은 ID, TimesTested, varA, varB로 구성됩니다.LINQ가 포함 된 'Multicolumn-List'의 중복 항목 제거

목록을 조인 한 다음 로컬 파일에 저장해야합니다. 중복 된 항목을 제거해야합니다.

문제는 'TimesTested'가 더 높은 값을 갖는 항목을 유지해야하기 때문에 ID를 검색하여 이미 있는지 확인할 수 없다는 것입니다.

나는 두리스트를 반복해서보고 싶지 않고 수동으로 값을 확인하고 싶지 않다. 그래서 저는 LINQ를 생각하고 있습니다.

4, 16, X, Y 
4, 19, X, Y 

만에 두 번째 행을 유지 :

은 내가이 주어진 경우 다음을 수행 할 수 있습니까? (LINQ를 사용하거나 다른 '똑똑한'방식으로)

예인 경우 어떻게 설명 할 수 있습니까?


이상하게도 로컬 파일에서 처음으로 값을로드 할 때 작동합니다. 은 첫 번째 저장 파일에 목록을 한 번 작성하는 즉시 내가 시도 하하지만 ... 원활하게 작동하는 것 같다 .. 나는 다음과 같은 오류 얻을 :이 내가 사용하고있는 코드가

Unable to cast object of type "WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[System.Int32,mcq_gui.clsEvaluation+History+EvaluationQuestionData],mcq_gui.clsEvaluation+History+EvaluationQuestionData]" to type Typ "System.Collections.Generic.List`1[mcq_gui.clsEvaluation+History+EvaluationQuestionData]" 

을 :

Friend Shared Function GetNewerEvalQs(list1 As List(Of EvaluationQuestionData), list2 As List(Of EvaluationQuestionData)) As List(Of EvaluationQuestionData) 
     Dim uniques As New List(Of EvaluationQuestionData) 
     Try 
      If list1.Count > 0 And list2.Count > 0 Then 
       uniques = list1.Concat(list2).GroupBy(Function(t) t.ID).[Select](Function(g) g.OrderByDescending(Function(t) t.TimesTested).First()) 
      Else 
       If list1.Count > 0 Then 
        Return list1 
       ElseIf list2.Count > 0 Then 
        Return list2 
       Else 
        Return Nothing 
       End If 
      End If 

      Return uniques 
     Catch ex As Exception 
      Debug.Print(ex.Message) 
      Return Nothing 
     End Try 
    End Function 

답변

0

한 가지 방법, Enumerable.GroupBy를 사용하여 다음 TimesTested에 따라 최고를 선택합니다.

var uniques = list1.Concat(list2) 
    .GroupBy(t => t.ID) 
    .Select(g => g.OrderByDescending(t => t.TimesTested).First()); 

편집 ... 또는 VB.NET (미안 해요, 난 t 먼저 태그를 참조 '를 didn를)에서 귀하의 방법 :

Friend Shared Function GetNewerEvalQs(list1 As List(Of EvaluationQuestionData), list2 As List(Of EvaluationQuestionData)) As List(Of EvaluationQuestionData) 
    list1 = If(list1 Is Nothing, New List(Of EvaluationQuestionData), list1) 
    list2 = If(list2 Is Nothing, New List(Of EvaluationQuestionData), list2) 
    If Math.Max(list1.Count, list2.Count) = 0 Then Throw New ArgumentException("One of both lists must contain data") 

    Dim newUniqueData = list1.Concat(list2). 
     OrderByDescending(Function(eqd) eqd.TimeTested). 
     GroupBy(Function(eqd) eqd.ID). 
     Select(Function(g) g.First()). 
     ToList() 
    Return newUniqueData 
End Function