[英]distinct values in a Linq to sql string.Join()
I have a table which contains the schedule for a class. 我有一张桌子,其中包含上课的时间表。 it contains the teacherid and name, datetime of the class and the course for that specific time.
它包含教师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
I want to write a linq to sql query which returns which teacher gives which courses, as such: 我想编写一个linq到sql查询,它返回哪个老师给哪个课程,例如:
Teachername courses
john math, french
jane english, math
jack history
I've gotten as far as the following 我已经做到以下内容
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)
};
but i'm getting the following output 但我得到以下输出
Teachername courses
john math, math, french
jane english, math
jack history
so john is getting the math value twice. 所以约翰两次获得数学值。 how do I make the string.Join function use distinct values?
如何使string.Join函数使用不同的值?
thanks 谢谢
没有用于distinct
查询语法,因此您应该更改为方法语法:
courses = string.Join(",", g.Select(i => i.CourseName).Distinct())
Add Distinct
to your select clause in String.Join
like: 将
Distinct
添加到String.Join
的select子句中, String.Join
所示:
courses = string.Join(",", (from i in g select i.CourseName).Distinct())
Or use method Syntax for select as well like: 或使用方法语法进行选择,例如:
courses = string.Join(",", (g.Select(i=> i.CourseName).Distinct())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.