HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Write nested loops as linq query

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqqueryloopswritenested

Problem

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 trains = GetTrains();

var wagonTrains = new Dictionary>();
foreach (Train t in trains)
{
  foreach (int w in t.WagonsInTrain)
  {
    if (!wagonTrains.ContainsKey(w))
    {
      wagonTrains.Add(w, new List());
    }
    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?

Solution

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

Code Snippets

var wagonTrains =
    (from train in trains
     from wagon in train.WagonsInTrain
     select new { train, wagon })
        .ToLookup(x => x.wagon, x => x.train);

Context

StackExchange Code Review Q#28964, answer score: 5

Revisions (0)

No revisions yet.