SeToY
SeToY

Reputation: 5895

LINQ: Selecting duplicate rows according to Column-Value

I'm trying to display those rows in my DataGrid, which share the same column-value.

For example, for Persons, who have the same Surname, I tried this:

dataGrid.ItemsSource = _dataContext.Addresses.GroupBy(a => a.SurName).Where(grp => grp.Count() > 1).Select(grp => grp.Key);

This works seemingly, as my WPF DataGrid contains rows after this command... Eventually it only displays empty rows, as no column is filled with a value.

Or I tried this with Persons, who have the same City:

dataGrid.ItemsSource = _dataContext.Addresses.GroupBy(a => a.City).Where(grp => grp.Count() > 1).Select(grp => grp.Key).Select(a => a);

Is there any proper way to do this?

Upvotes: 6

Views: 5969

Answers (1)

Chris Shain
Chris Shain

Reputation: 51359

You are only selecting the key in your example:

dataGrid.ItemsSource = _dataContext.Addresses.GroupBy(a => a.SurName).Where(grp => grp.Count() > 1).Select(grp => **grp.Key**);

What I assume you are trying to do is to select the whole row:

dataGrid.ItemsSource = _dataContext.Addresses.GroupBy(a => a.SurName).Where(grp => grp.Count() > 1).SelectMany(grp => grp.Select(r=>r));

To compare first and last names:

dataGrid.ItemsSource = _dataContext.Addresses.GroupBy(a => new Tuple<String, String>(a.ForeName, a.SurName)).Where(grp => grp.Count() > 1).SelectMany(grp => grp.Select(r=>r));

EDIT: For L2E, you can (I think) use anonymous types:

dataGrid.ItemsSource = _dataContext.Addresses.GroupBy(a => new { a.ForeName, a.SurName }).Where(grp => grp.Count() > 1).SelectMany(grp => grp.Select(r=>r));

The above could be incorrect- not 100% sure.

Upvotes: 11

Related Questions