Write nested loops as linq query 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&lt;Train&gt; trains = GetTrains();

var wagonTrains = new Dictionary&lt;int, List&lt;Train&gt;&gt;();
foreach (Train t in trains)
{
  foreach (int w in t.WagonsInTrain)
  {
    if (!wagonTrains.ContainsKey(w))
    {
      wagonTrains.Add(w, new List&lt;Train&gt;());
    }
    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?
create a lookup of all tracked trains for each wagon


That'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 =&gt; x.wagon, x =&gt; x.train);