我无法对从数据库中检索到的数据进行分组,该数据由于具有我不需要的数据的列而具有重复。我试图使用distinct或group by来摆脱裁员。
fixed
它将返回学生的姓名,但也会根据当天可用的课程重复学生记录。我只想获得今天和明天上课的学生名单。
我尝试过:
var students= db.student.Distinct().Where(c => c.classdate== tomorrow || c.classdate== todayd).ToList();
以上似乎只返回按列和
分组的结果集students.GroupBy(x => new { x.Fn ame, x.classdate});
似乎与返回类型不兼容。
答案 0 :(得分:1)
如果您想要小组的第一个学生,可以使用此LINQ查询:
students.GroupBy(x => new { x.Fname, x.classdate}).Select(grp => grp.First);
这将产生一个通用IEnumerable<T>
,其中T
是您的煽动类型。
答案 1 :(得分:1)
根据我的理解,您希望获得今天或明天都有课程的所有学生姓名。如果是这种情况,则LINQ表达式不准确。您的表达式应该按顺序进行过滤,选择和不同的操作。像这样:
db.student.Where(<condition here>).Select(<columns to select here>).Distinct(<comparer here; optional>)
答案 2 :(得分:0)
表示&#34;与#34;不同你可以分组,并从每组中选择第一行。
所以在模特中:
return students.GroupBy(x => new { x.Fname, x.classdate}).Select(x => x.First()).ToList();
在视图中:
@model IEnumerable<student>
答案 3 :(得分:0)
只需根据需要从学生表中选择列并使用Distinct(),就像你的查询应该是明智的
var students =(来自db.student.Where中的objSql(t =&gt; t.classdate ==明天|| t.classdate == todayd) 选择新的CustomObject(){StudentName = objSql.StudentName})。Distinct()。ToList();
答案 4 :(得分:0)
我想你应该喜欢这个。
context.Student.Select(i => new { i.Fn, i.classdate }).Where(c => c.classdate == tomorrow || c.classdate == todayd).Distinct();
如果您运行此代码,它会在数据库中生成以下查询。
exec sp_executesql N'SELECT
[Distinct1].[C1] AS [C1],
[Distinct1].[Fn] AS [Fn],
[Distinct1].[classdate] AS [classdate]
FROM ( SELECT DISTINCT
[Extent1].[Fn] AS [Fn],
[Extent1].[classdate] AS [classdate],
1 AS [C1]
FROM [dbo].[Student] AS [Extent1]
WHERE [Extent1].[classdate] IN (@p__linq__0,@p__linq__1)
) AS [Distinct1]',N'@p__linq__0 datetime2(7),@p__linq__1 datetime2(7)',@p__linq__0='2018-04-17 00:00:00',@p__linq__1='2018-04-16 00:00:00'