LINQ选择不同的集合并检索不同的列 [英] LINQ select distinct set and retrive different column

查看:63
本文介绍了LINQ选择不同的集合并检索不同的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够执行以下查询:

I want to be able to execute the following query:

select distinct studentname, subject, grade from studenttable;

student表具有以下字段:

The student table has the following fields:

studentid
studentname
subject
grade

我现在使用的linq查询是:

The linq query I have now is:

var students=dc.Select(s => new {s.studentname, s.subject, s.grade}).Distinct();

dc是数据上下文.

该查询有效,但是如何在满足studentname, subject, grade集合的特殊条件的同时让学生id呢?

This query works, but how do I get the student id while still satisfying the distinct condition on the studentname, subject, grade set?

推荐答案

我相信您的设计已损坏,但我会回答您的特定问题....

I believe your design is broken, but I'll answer your specific question....

我假设您正在尝试按名称,主题和年级进行分组,并检索每组的第一位有代表性的学生.

I'm assuming you're trying to group by name, subject and grade, and retrieve the first representative student of each group.

在这种情况下,您可以按元组进行分组.元组将为您免费提供EqualsGetHashCode方法,因此可以在组操作中使用.

In this case, you can group by Tuples. A tuple will give you an Equals and GetHashCode method for free, so can be used in Group operations.

IEnumerable<Student> distinctStudents = students
                                           .AsEnumerable()
                                           .GroupBy(s => Tuple.Create
                                                               (
                                                                   s.studentname, 
                                                                   s.subject, 
                                                                   s.grade
                                                               )
                                                          )
                                           .Select(g => g.First()); /// Returns the first student of each group

以下是一个点网小提琴示例:

Here is a dot net fiddle example: https://dotnetfiddle.net/7K13DJ

这篇关于LINQ选择不同的集合并检索不同的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆