情况如下:
在某个学校,某个班级分为两组:
第一个学习英语,另一个学习德语,但分配给班级的时间是相同的。
我有虚拟情况,IList
(持有DB的记录)我对同一类学生有相同的Time
课程,我需要使用C#和这些对象加入最好是LINQ。
换句话说,当这些对象具有相同的Time属性时,我需要将一个对象合并到另一个对象中。最终结果将显示在学校时间表(时间表)中,问题是避免重复记录。
我目前有类似的东西:
var lessons = KlassLesson.GetKlassSchedule(userProfile.Preferences.MyClassID, dayOfWeek);
lessons = JoinDoubleLessons(lessons);
private List<KlassLesson> JoinDoubleLessons(List<KlassLesson> lessons)
{
// ?????
}
答案 0 :(得分:0)
我应该说我对你的问题不是很清楚,因为你没有回答我的问题,我认为只有一个列表,而且这个列表包含一些重复的“AddedDate”值
以下是完整的功能代码。我开了几节课。请注意,我已经从变量“testDateAndTime”中分配了其中两个课程的AddedDate值。标题的教训 AAAAA 和 BBBBB
class Program
{
static void Main(string[] args)
{
var testDateAndTime = DateTime.Now;
var lessons = new Lesson[] {
new Lesson { Title="A", Subject="English", AddedDate = DateTime.Now.AddMinutes(1)},
new Lesson { Title="AA", Subject="English", AddedDate = DateTime.Now.AddDays(2)},
new Lesson { Title="AAA", Subject="English", AddedDate = DateTime.Now.AddDays(3)},
new Lesson { Title="AAAA", Subject="English", AddedDate = DateTime.Now.AddDays(4)},
new Lesson { Title="AAAAA", Subject="English", AddedDate = testDateAndTime},
new Lesson { Title="B", Subject="German", AddedDate = DateTime.Now.AddMinutes(5)},
new Lesson { Title="BB", Subject="German", AddedDate = DateTime.Now.AddDays(6)},
new Lesson { Title="BBB", Subject="German", AddedDate = DateTime.Now.AddDays(7)},
new Lesson { Title="BBBB", Subject="German", AddedDate = DateTime.Now.AddDays(8)},
new Lesson { Title="BBBBB", Subject="German", AddedDate = testDateAndTime}
};
var groupedLessons = from l in lessons
group l by l.AddedDate into g
select new { AddedDate = g.Key, Lessons = g };
foreach (var k in groupedLessons)
{
Console.WriteLine("Added Date: " + k.AddedDate);
foreach (var l in k.Lessons)
{
Console.WriteLine("\t Lesson Title: " + l.Title);
}
}
}
}
public class Lesson
{
public string Title { get; set; }
public string Subject { get; set; }
public DateTime AddedDate { get; set; }
}
我得到的输出是:
Added Date: 2/2/2011 3:25:36 AM
Lesson Title: A
Added Date: 2/4/2011 3:24:36 AM
Lesson Title: AA
Added Date: 2/5/2011 3:24:36 AM
Lesson Title: AAA
Added Date: 2/6/2011 3:24:36 AM
Lesson Title: AAAA
Added Date: 2/2/2011 3:24:36 AM
Lesson Title: AAAAA
Lesson Title: BBBBB
Added Date: 2/2/2011 3:29:36 AM
Lesson Title: B
Added Date: 2/8/2011 3:24:36 AM
Lesson Title: BB
Added Date: 2/9/2011 3:24:36 AM
Lesson Title: BBB
Added Date: 2/10/2011 3:24:36 AM
Lesson Title: BBBB
其中显示了2/2/2011 3:24:36 AM的两个课程(AAAAA和BBBBB) 这是我所期待的。但话说回来,我不确定你在期待什么。我不确定你的意思是“合并”。您对此解决方案的看法是已经识别(并分组)重复项,因此您现在可以采用重复项并以您认为合适的方式“合并”它们。
你可以修改sql表达式,这样你只得到像这样的重复项:
var groupedLessons = from l in lessons
group l by l.AddedDate into g
where g.Count() > 1
select new { AddedDate = g.Key, Lessons = g };