【问题标题】:distinct values in a Linq to sql string.Join()Linq to sql string.Join() 中的不同值
【发布时间】:2015-03-09 18:37:44
【问题描述】:

我有一张包含课程时间表的表格。它包含教师 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 查询,它返回哪个老师教了哪些课程,例如:

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 函数使用不同的值?

谢谢

【问题讨论】:

    标签: c# .net linq linq-to-sql


    【解决方案1】:

    distinct 没有查询语法,所以你应该改成方法语法:

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

    【讨论】:

      【解决方案2】:

      Distinct 添加到String.Join 中的选择子句中,例如:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-26
        • 1970-01-01
        • 2010-10-08
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 2011-04-01
        相关资源
        最近更新 更多