Linq to sql string.Join() 中的不同值
distinct values in a Linq to sql string.Join()
我有一个 table,其中包含 class 的时间表。它包含 class 的教师 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 to sql query which returns which teacher to which courses, as such:
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 子句,例如:
courses = string.Join(",", (from i in g select i.CourseName).Distinct())
或者使用 select 的方法语法,如:
courses = string.Join(",", (g.Select(i=> i.CourseName).Distinct())
我有一个 table,其中包含 class 的时间表。它包含 class 的教师 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 to sql query which returns which teacher to which courses, as such:
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 子句,例如:
courses = string.Join(",", (from i in g select i.CourseName).Distinct())
或者使用 select 的方法语法,如:
courses = string.Join(",", (g.Select(i=> i.CourseName).Distinct())