Home > Net >  Linq: select a list by concatenating values from two (or more) fields of the same type
Linq: select a list by concatenating values from two (or more) fields of the same type

Time:05-27

I have the following classes:

public class Line
{
    public List<Trip> Trips;
}

public class Trip
{
    public TimeSpan Departure { get; set; }
    public TimeSpan Arrival { get; set; }
}

and an object List<Line> lines.

Using Linq I'm trying to find a list of all times in trips, regardless of whether it's departure time or arrival time, possibly without duplicates.

So for example:

DEPARTURE | ARRIVAL
  05:11   |  12:32
  08:00   |  11:00
  12:32   |  14:00

should return:
05:11
12:32
08:00
11:00
14:00     

I tried something like this:

var l = lines
    .SelectMany(t => t.Trips)
    .Select(x => x.Departure).Concat(x => x.Arrival);

or

var l = lines
    .SelectMany(t => t.Trips)
    .SelectMany(x => new { x.Departure, x.Arrival });

but they didn't work.

I found this answer but I cannot adapt it to my situation.

CodePudding user response:

This will get you an array of TimeSpan and remove duplicates:

var l = lines.SelectMany(a => a.Trips)
    .Select(b => new TimeSpan[] { b.Arrival, b.Departure})
    .SelectMany(c => c)
    .Distinct()
    .ToArray();

If you want to keep the duplicates, remove the call to Distinct()

var l = lines.SelectMany(a => a.Trips)
   .Select(b => new TimeSpan[] { b.Arrival, b.Departure})
   .SelectMany(c => c)
   .ToArray();

If you want them Ordered:

var l = lines.SelectMany(a => a.Trips)
   .Select(b => new TimeSpan[] { b.Arrival, b.Departure})
   .SelectMany(c => c)
   .Distinct()
   .OrderBy(d => d)
   .ToArray();

CodePudding user response:

I think this might be the simplest way

List<Line> result = line1.Select(model => model.Departure)
                         .Union(line2.Select(model => model.Arrival))
                         .ToList();

CodePudding user response:

var selection = lines.SelectMany(line => line.Trips).Select(t => t);
var distinctFlat = selection.Select(t => t.Arrival).Concat(selection.Select(t => t.Departure)).Distinct().ToList();
  • Related