LINQ: select duplicate rows according to column value

I am trying to display these rows in my DataGrid that have the same column value.

For example, for people having the same last name, I tried this:

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

It looks like my WPF DataGrid contains rows after this command ... In the end, it only displays empty rows, since 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 a proper way to do this?

+5
source share
1 answer

You select only the key in your example:

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

I assume what you are trying to do is select the whole line:

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

To compare the first and last name:

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

, 100% .

+9

All Articles