这是我上课的课程:
public class Schedule
{
public string mintime { get; set; }
public string maxtime { get; set; }
public string weekday { get; set; }
}
我得到了一份重复工作日的时间表,如
List<Schedule> list = new List<Schedule> {
new Schedule { mintime = "01.01.2012", maxtime = "05.01.2012", weekday = "1" },
new Schedule { mintime = "05.01.2012", maxtime = "10.01.2012", weekday = "1" },
new Schedule { mintime = "10.01.2012", maxtime = "20.01.2012", weekday = "2" },
new Schedule { mintime = "01.02.2012", maxtime = "10.02.2012", weekday = "2" },
new Schedule { mintime = "01.03.2012", maxtime = "10.03.2012", weekday = "3" },
new Schedule { mintime = "01.04.2012", maxtime = "10.04.2012", weekday = "4" }
};
我如何获得List&gt;所有组合如:
List<List<Schedule>> list = new List<List<Schedule>> {
new List<Schedule> {
new Schedule { mintime = "01.01.2012", maxtime = "05.01.2012", weekday = "1" },
new Schedule { mintime = "10.01.2012", maxtime = "20.01.2012", weekday = "2" },
new Schedule { mintime = "01.03.2012", maxtime = "10.03.2012", weekday = "3" },
new Schedule { mintime = "01.04.2012", maxtime = "10.04.2012", weekday = "4" }
},
new List<Schedule> {
new Schedule { mintime = "01.01.2012", maxtime = "05.01.2012", weekday = "1" },
new Schedule { mintime = "01.02.2012", maxtime = "10.02.2012", weekday = "2" },
new Schedule { mintime = "01.03.2012", maxtime = "10.03.2012", weekday = "3" },
new Schedule { mintime = "01.04.2012", maxtime = "10.04.2012", weekday = "4" }
},
new List<Schedule> {
new Schedule { mintime = "05.01.2012", maxtime = "10.01.2012", weekday = "1" },
new Schedule { mintime = "10.01.2012", maxtime = "20.01.2012", weekday = "2" },
new Schedule { mintime = "01.03.2012", maxtime = "10.03.2012", weekday = "3" },
new Schedule { mintime = "01.04.2012", maxtime = "10.04.2012", weekday = "4" }
},
new List<Schedule> {
new Schedule { mintime = "05.01.2012", maxtime = "10.01.2012", weekday = "1" },
new Schedule { mintime = "01.02.2012", maxtime = "10.02.2012", weekday = "2" },
new Schedule { mintime = "01.03.2012", maxtime = "10.03.2012", weekday = "3" },
new Schedule { mintime = "01.04.2012", maxtime = "10.04.2012", weekday = "4" }
},
};
是否可以使用LINQ获取它?
我的问题的主要议题是建立时间表列表。每个时间表应包括星期一,星期二,星期三,星期四,星期五,星期六和星期日一次。 我需要使用一个更常见的列表来构建这样的列表,该列表包含星期一,星期三等许多时间表。
答案 0 :(得分:2)
使用Eric Lippert
的{{3}}
List<List<Schedule>> newList = CartesianProduct(list.GroupBy(l => l.weekday))
.Select(x => x.ToList())
.ToList();
-
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }));
}