所以我有这些数据示例

projects   startdate    enddate
prj A      01 Jan 2019  10 Feb 2019
prj B      29 Jan 2019  15 Mar 2019
prj C      21 Mar 2019  02 May 2019
prj D      07 May 2019  10 Jun 2019
prj E      11 Jun 2019  30 Jul 2019


而且我想使用linq lambda使每个对象包含连续项目列表的列表对象
分组结果大致是这样的

[
   [prj A, prj B],
   [prj C],
   [prj D, prj E]
]



prj A和B被分组,因为日期范围prj A与prj重叠

由于结束日期prj B和开始日期prj C之间有空格,因此
prj C在不同的组
prj D和E被分组,因为开始日期
prj E是结束日期prj D的第二天


那么如何使用linq lambda创建分组呢?
谢谢

最佳答案

您无法通过Linq GroupBy它们,因为组中的每个项目可能在其他项目中没有共同的分组密钥,或者无法找到,而是在两个邻域之间仅存在一个共同的密钥。 Try another approach:

var result = new List<List<string>>();
var projects = new List<Project>
{
    new Project{ Name = "prj A",
        startdate = new DateTime(2019, 1, 1), enddate = new DateTime(2019, 2, 10) },
    new Project{ Name = "prj B",
        startdate = new DateTime(2019, 1, 29), enddate = new DateTime(2019, 3, 15) },
    new Project{ Name = "prj C",
        startdate = new DateTime(2019, 3, 21), enddate = new DateTime(2019, 5, 2) },
    new Project{ Name = "prj D",
        startdate = new DateTime(2019, 5, 7), enddate = new DateTime(2019, 6, 10) },
    new Project{ Name = "prj E",
        startdate = new DateTime(2019, 6, 11), enddate = new DateTime(2019, 7, 30) }
};
projects = projects.OrderBy(x => x.startdate).ToList();

for (var i = 0; i < projects.Count; i++)
{
    var project = projects[i];
    if (projects[0] != project
        &&
        (project.startdate - projects[i - 1].enddate).TotalDays < 2)
        result.Last().Add(project.Name);
    else
        result.Add(new List<string> { project.Name });
}

foreach(var gr in result)
    Console.WriteLine(String.Join(", ", gr));
//prj A, prj B
//prj C
//prj D, prj E

关于c# - 如何在linq中加入连续日期范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56963596/

10-10 21:40