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?
EDIT:
Wow, exactly what I was looking for!
I went with a combination of the answers below and added comments:
// every wagon keyed to a list of trains its been seen on
ILookup<string, TrackedTrain> trainsByWagon = trains.SelectMany(train => train.SeenWagons, // Collection: get every wagon seen on every train
(train, wagon) => new { wagon, train }) // Result: list every wagon sighting plus the train it was seen on
.ToLookup(wagonTrainPair => wagonTrainPair.wagon, // Key: group the wagon-plus-train sightings by wagon
wagonTrainPair => wagonTrainPair.train); // Element: in each wagon group put the trains it was seen on