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