Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 729
SeToY Avatar asked Feb 10 '12 16:02

SeToY


1 Answers

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.

like image 160
Chris Shain Avatar answered Oct 20 '22 13:10

Chris Shain