Is there An Efficient way of combining two collections?

I have classes as follows:

public class Root
{
  public int Id {get;set;}
  public string PlayerName{get;set;}      
}

public class Scores:Root
{
  public int GameT{get;set;}
  public int GameZ{get;set;}
}

public class Experience:Root
{
  public int ExT{get;set;}
  public int ExZ{get;set;}
}

public class Total:Root
{
   public int TotalT{get;set;}
   public int TotalZ{get;set}
}

TotalT and TotalZ are got from adding GameT, ExT and GameZ, ExZ respectively. I have an observable collection of scores and Experience from which I want to create another collection of Total, here is what I have done so far:

public ObservableCollection<Total> GetTotal(ObservableCollection<Scores>    scores,ObservableCollection<Experience> experiences)
{
var tc= new ObservableCollection<Total>();
foreach(var scr in scores)
{
  foreach(var exp in experiences)
  {

    if(scr.Id==exp.Id)
    {
     var tt= new Total{
       Id=scr.Id,
       Name=scr.PlayerName,
       TotalT=scr.GameT+exp.Ext,
       TotalZ=scr.GameZ+exp.Exz
       };
     tc.Add(tt);
    }
  }
 }
 return tc;
}

It works but it is too slow, especially when the records begin to hit hundreds. Is there a better way?

Jon Skeet
people
quotationmark

It looks like you just want a LINQ inner join:

var query = from score in scores
            join exp in experiences on score.Id equals exp.Id
            select new Total {
                Id = score.Id,
                Name = score.PlayerName,
                TotalT = score.GameT + exp.Ext,
                TotalZ = score.GameZ + exp.Exz
            };
return new ObservableCollection<Total>(query);

That will be more efficient by iterating over all the experiences to start with, collecting them by ID, then iterating over the scores, matching each score with the collection of associated experiences. Basically it turns an O(M * N) operation into an O(M + N) operation.

people

See more on this question at Stackoverflow