如果我有这样的日期列表:
List<DateTime> {5-10-2014,6-10-2014,7-10-2014}
我有这样的 session 列表:
List<int> {1,2,3,4,5,6}
考虑到每个日期按顺序有两个 session (使用 linq),如何将 session 映射到日期。
我想要这样的结果:
5-10-2014 1
5-10-2014 2
6-10-2014 3
6-10-2014 4
7-10-2014 5
7-10-2014 6
最佳答案
这是您可以使用 GroupJoin
实现的一种方法:
var groupedDates = dates
.Select((date, index) => new { Date = date, Index = index })
.GroupJoin(
numbers,
dateWithIndex => dateWithIndex.Index,
num => (num - 1) / 2,
(dateWithIndex, nums) => new[]
{
new { Date = dateWithIndex.Date, Number = nums.First() },
new { Date = dateWithIndex.Date, Number = nums.Last() }
})
.SelectMany(grp => grp);
示例: https://dotnetfiddle.net/2IIKhj
这是它的工作原理:
- 将日期列表投影到包含每个日期的索引和日期本身的新序列中
GroupJoin
带有数字列表的集合。要将两者相关联,请使用我们从步骤 1 中获得的Index
作为日期,并使用(num - 1)/2
,因为Index
是零基础。- 要构建结果,请创建一个包含两项的新数组,一项对应与日期关联的每个数字。
- 最后,调用
SelectMany
来展平序列。
关于c# - 如何使用 linq 映射两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425728/