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();
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());
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!