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 wagonIEnumerable<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?
Write nested loops as linq query
c#;linq
create a lookup of all tracked trains for each wagonThat's pretty much what the ToLookup() method is for. You just need a bit more LINQ  to get a collection of (train, wagon) pairs, so that ToLookup() can work:var wagonTrains =    (from train in trains     from wagon in train.WagonsInTrain     select new { train, wagon })        .ToLookup(x => x.wagon, x => x.train);