I am tracking trains and trying to identify individual trains seen multiple times at different points through the IDs of the wagons on them when spotted.
// create a lookup of all tracked trains for each wagon
IEnumerable<Train> trains = GetTrains();
var wagonTrains = new Dictionary<int, List<Train>>();
foreach (Train t in trains)
{
foreach (int w in t.WagonsInTrain)
{
if (!wagonTrains.ContainsKey(w))
{
wagonTrains.Add(w, new List<Train>());
}
wagonTrains[w].Add(t);
}
}
Is there a better way do to what I am doing in this code segment? Perhaps some chained linq operations? Is there a particular name for the kind of operation I am using here?