patterncsharpMinor
Write nested loops as linq query
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.
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
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
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.