Linq:select 通过连接来自相同类型的两个(或更多)字段的值的列表

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

我有以下 类:

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

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

和一个对象 List<Line> lines

我正在尝试使用 Linq 查找旅行中所有时间的列表,无论是出发时间还是到达时间,可能没有重复。

例如:

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     

我试过这样的事情:

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

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

但是他们没有用。

我找到了 this answer 但我无法根据自己的情况调整它。

这将为您提供 TimeSpan 的数组并删除重复项:

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

如果您想保留重复项,请删除对 Distinct()

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

如果你想要它们 已订购:

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

我认为这可能是最简单的方法

List<Line> result = line1.Select(model => model.Departure)
                         .Union(line2.Select(model => model.Arrival))
                         .ToList();
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();