简体   繁体   English

相当于SELECT DISTINCT的LINQ

[英]LINQ Equivalent of SELECT DISTINCT

I'm wanting to only display a list of CourseNo with no duplicates using LINQ, but I can't quite figure the syntax out. 我只想显示一个使用LINQ的没有重复的CourseNo列表,但是我不太清楚语法。

        this.Distinct_CourseNo = (from c in Roster_Sections
                                  select c).Distinct(CourseNo).ToList;

The SQL equivalent would be something along the lines of: 与SQL等效的方式如下:

SELECT DISTINCT CourseNo
FROM Roster_Sections

using select c will include all columns in the Roster_Sections , thus Distinct() will not work if atleast one row in a column is different from the other row. 使用select c将包括Roster_Sections所有列,因此,如果一列中至少有一行与另一行不同,则Distinct()将不起作用。

this.Distinct_CourseNo = (from c in Roster_Sections
                          select c.CourseNo).Distinct().ToList();

or 要么

this.Distinct_CourseNo = Roster_Sections.Distinct(c => c.CourseNo).ToList();

All the provided answers are applicable only if you have moreLINQ . 仅当您具有moreLINQ时,所有提供的答案才适用。 However, you can try this instead: 但是,您可以尝试以下方法:

this.Distinct_CourseNo = (from c in Roster_Sections
                          group c by c.CourseNo into g
                          select g.First()).ToList();

You'd pass Distinct a lambda describing what defines distinctness: 您将通过Distinct一个lambda来描述定义差异性的内容:

this.Distinct_CourseNo = Roster_Sections.Distinct(x => x.CourseNo).ToList();

If you mean to get a list of unique course numbers as opposed to a list of unique courses based off course number, 今 草 顿 웃's answer is the way to go. 如果您想要获取唯一的课程号列表,而不是基于课程号的唯一课程列表,那么今草顿顿的答案就是解决之道。

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

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