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

How to Delete Duplicate Records in LINQ Based on a Specific Field?

Mary-Kate Olsen
Release: 2025-01-03 06:10:40
Original
415 people have browsed it

How to Delete Duplicate Records in LINQ Based on a Specific Field?

Deleting Duplicates in Linq Based on a Table's Field

In Linq, the distinct operator offers a straightforward way to eliminate duplicate records from a table. However, by default, it compares the entire records, not just specific fields.

When you intend to filter duplicate records based solely on a single field, such as r.Text in your example, a modified approach is required.

Using the query you provided:

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

will prevent duplicates, but based on the combined content of all fields, not just r.Text.

To achieve your desired outcome, consider the following query:

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

This query will group the table1 by the Text field using GroupBy. Within each group, it selects the first item using FirstOrDefault(). The resulting collection will contain rows where the Text field is distinct.

The above is the detailed content of How to Delete Duplicate Records in LINQ Based on a Specific Field?. 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