C#-使用SelectMany合并多个列表

时间:2018-11-12 17:49:44

标签: c# linq merge

截至目前,我使用以下代码合并两个List<string>列表并按时间戳对其进行排序

var list = report[0];  
var list2 = report[1];
var result = list
    .Union(list2)
    .Select(x =>
    {  return new {Log = x, Time = TimeSpan.Parse(x.Split(' ')[0])}; })
    .OrderBy(x => x.Time)
    .ToList(); 

现在的问题是我必须处理两个以上的列表,最多n。我研究了SelectMany的示例,但它似乎不支持与Select相同的功能。我计划执行此操作的另一种方法是使用foreach循环,但这似乎不是一种有效的方法,尤其是当列表变大时。
修改(添加了示例数据和预期结果)
list1示例如下所示:
11:03:01:003 INFO some event has occurred 11:03:31:004 DEBUG another event has occurred 11:04:01:015 INFO third event has occurred
list2示例如下所示:
11:03:16:003 INFO fourth event has occurred 11:03:32:025 DEBUG fifth event has occurred 11:03:54:023 INFO sixth event has occurred
因此,可以有多个类似的列表。这两个列表的预期合并将以以下方式显示:
11:03:01:003 INFO some event has occurred 11:03:16:003 INFO fourth event has occurred 11:03:31:004 DEBUG another event has occurred 11:03:32:025 DEBUG fifth event has occurred 11:03:54:023 INFO sixth event has occurred 11:04:01:015 INFO third event has occurred

4 个答案:

答案 0 :(得分:4)

可以在此处使用SelectMany

// suppose reports is of type List<List<SomeClass>>
reports.SelectMany(x => x)
    .Select(x =>
        {  return new {Log = x, Time = TimeSpan.Parse(x.Split(' ')[0])}; })
    .OrderBy(x => x.Time)
    .ToList(); 

添加一个.Distinct调用将使其具有与Union相同的效果:

reports.SelectMany(x => x).Distinct()
    .Select(x =>
        {  return new {Log = x, Time = TimeSpan.Parse(x.Split(' ')[0])}; })
    .OrderBy(x => x.Time)
    .ToList(); 

或者,继续使用Union

IEnumerable<SomeClass> query = reports[0];
for (int i = 1 ; i < reports.Length ; i++) {
   query = query.Union(reports[i]);
}

答案 1 :(得分:0)

我假设reportIEnumerable的{​​{1}}。所以你需要这样的东西:

IEnumerable<string>

report.SelectMany(l => l.Select(x => new {Log = x, Time = TimeSpan.Parse(x.Split(' ')[0])})) .OrderBy(x => x.Time) .ToList(); 将合并SelectMany的所有结果,然后按时间排序。

编辑:

由于已经指出l.Select会删除重复项,因此您需要添加Union才能获得相同的结果:

Distinct

答案 2 :(得分:0)

有几种解决方案,其中一种可能是:

List<IEnumerable<string>> allLists = new List<IEnumerable<string>>();
            allLists.Add(report[0]);
            allLists.Add(report[1]);
            allLists.Add(report[2]);

            var result = allLists.SelectMany(l => l.Select(x => new
            {
                Log = x,
                Time = TimeSpan.Parse(x.Split(' ')[0])
            })).OrderBy(x => x.Time)
            .ToList();

答案 3 :(得分:-1)

不确定为什么其他答案还有额外的.Select

var result = report
       .SelectMany(l => l, (l, x) => new { Log = x, Time = TimeSpan.Parse(x.Split(' ')[0]) })
       .Distinct().OrderBy(x => x.Time).ToList();