繁体   English   中英

Linq to sql string.Join()中的不同值

[英]distinct values in a Linq to sql string.Join()

我有一张桌子,其中包含上课的时间表。 它包含教师ID和名称,课程的日期时间以及该特定时间的课程。

teacherid    teachername    startdate         coursename
1            john           9/1/2014 10:00    math
2            john           9/2/2014 10:00    math
3            jane           9/3/2014 10:00    english
4            john           9/4/2014 10:00    french
5            jack           9/5/2014 10:00    history
6            jane           9/6/2014 10:00    math

我想编写一个linq到sql查询,它返回哪个老师给哪个课程,例如:

Teachername    courses
john           math, french
jane           english, math
jack           history

我已经做到以下内容

var _classes = from _c in dbContext.classes                           
                       where _c.StartDate < System.DateTime.Now
                       group _c by new
                       {
                           _c.TeacherId,
                           _c.TeacherName,
                           _c.CourseName
                       } into g
                       select new
                       {
                           g.Key.TeacherName,
                           courses = string.Join(",", from i in g select i.CourseName)
                       };

但我得到以下输出

Teachername    courses
john           math, math, french
jane           english, math
jack           history

所以约翰两次获得数学值。 如何使string.Join函数使用不同的值?

谢谢

没有用于distinct查询语法,因此您应该更改为方法语法:

courses = string.Join(",", g.Select(i => i.CourseName).Distinct())

Distinct添加到String.Join的select子句中, String.Join所示:

courses = string.Join(",", (from i in g select i.CourseName).Distinct())

或使用方法语法进行选择,例如:

courses = string.Join(",", (g.Select(i=> i.CourseName).Distinct())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM