Home > Database > Mysql Tutorial > How to Select Distinct Records Based on a Specific Field in LINQ?

How to Select Distinct Records Based on a Specific Field in LINQ?

Susan Sarandon
Release: 2025-01-03 06:40:38
Original
790 people have browsed it

How to Select Distinct Records Based on a Specific Field in LINQ?

Selecting Distinct Records Based on a Single Field in LINQ

When working with data in LINQ, it may be necessary to filter out duplicate records, ensuring only unique values are returned. However, instead of eliminating entire duplicated rows, it may be desirable to perform this operation based on a specific field or property.

Basic Distinct Query

The following LINQ query demonstrates a basic way to use the Distinct() method to eliminate duplicate rows:

var query = (from r in table1
orderby r.Text
select r).Distinct();
Copy after login

This query retrieves all rows from the table1 sorted by the Text field and then removes any duplicates from the resulting set.

Distinct on Specific Field

But what if the goal is to return only rows where a particular field, such as Text, contains unique values? To achieve this, one option is to use the GroupBy() method followed by the Select() method:

table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
Copy after login

In this query, the table1 is first grouped by the Text field, creating groups for each unique Text value. Then, for each group, the FirstOrDefault() method is used to select the first row. The result is a collection of rows where the Text field contains distinct values.

The above is the detailed content of How to Select Distinct Records Based on a Specific Field in LINQ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template