2015-09-03 243 views
0

我目前正在研究一個項目並遇到了麻煩。從列表中刪除重複的對象

我參加了足球隊的一個未格式化的string[],我試圖過濾數據並以更多的價格格式返回。

我很好,大部分(拆分字符串以獲取相關的值和排序格式),除了我創建了一個Team對象,其中包含大部分這些數據,當我通過原始字符串循環創建一個每次我看到一個團隊名稱時都會有新的團隊對象。然後我檢查一下,看看我是否曾經看過那個對象,如果我有我不創建一個新的對象。在創建團隊或跳過該部分後,我將相關信息添加到團隊對象並繼續。

我的問題是我用來保存最終團隊信息的列表有很多重複的意思是我檢查對象是否存在不起作用。該代碼是:

分割字符串後,

 List<Team> teams = new List<Team>(); 

     for (int i = 1; i <= matches.Length - 1; i++) 
     { 
      string fullStr = matches[i]; 

      string[] score = fullStr.Split(','); 

      string[] team1 = score[0].Split('!'); 
      string team1Name = team1[0]; 

      Team teams1 = new Team(team1Name); 
      if (teams.Contains(teams1) != true) 
      { 
       teams.Add(teams1); 
      } 

      string team1Score = team1[1]; 
      int team1ScoreInt = int.Parse(team1Score); 

      string[] team2 = scores[1].Split('!'); 
      string team2Name = team2[1]; 


      Team teams2 = new Team(team2Name); 

      if (!teams.Contains(teams2)) 
      { 
       teams.Add(teams2); 
      } 

當我打印列表中我得到的格式,我想要的,但多個德等。而只有1場比賽的比分等,而不是他們全部加入1德國隊對象。

任何想法如何我可以停止重複,並保持每次我看到該團隊名稱時只使用1隊對象?

感謝

+0

請不要破壞你的帖子。 – durron597

回答

0

您可以實現的IEqualityComparer爲Team類和檢查基於其值的對象相等。像下面的東西。

using System.Collections.Generic; 
    public class Team{ 
     public string Name {get;set;} 
     public int score {get;set;} 
     } 
     //Create some dummy data 
    public List<Team> lstTeam = new List<Team>{ 
     new Team{Name="A", score=1}, 
     new Team{Name="A", score=1}, 
     new Team{Name="B", score=1}, 
     new Team{Name="C", score=2}, 
     new Team{Name="A", score=2}, 
     new Team{Name="C", score=2} 

     }; 

    List<Team> lstDistictTeams = lstTeam.Distinct<Team>(new DistinctComparer()).ToList(); 
    foreach(Team t in lstDistictTeams) 
    { 
     Console.WriteLine("Team {0} has Score {1}",t.Name,t.score); 
     } 

//This class provides a way to compare two objects are equal or not 
    public class DistinctComparer : IEqualityComparer<Team> 
     { 
      public bool Equals(Team x, Team y) 
      { 
       return (x.Name == y.Name && x.score == y.score); // Here you compare properties for equality 
      } 
      public int GetHashCode(Team obj) 
      { 
       return (obj.Name.GetHashCode() + obj.score.GetHashCode()); 
      } 
     } 

這裏運行例如:http://csharppad.com/gist/6428fc8738629a36163d

0

貌似問題是你要創建的團隊爲每個結果的名稱的新Team對象。

然後,當您與列表進行比較以查看它是否包含時,您將檢查列表中是否有對該對象的引用,並且您剛創建它時,不會有,因此您創建的每個Team對象都將添加到列表中。

您需要檢查列表是否包含名稱爲Team的對象,而不是僅檢查對象的實例。