2012-02-10 65 views
5

我想在我的DataGrid中显示那些共享相同列值的行。LINQ:根据列值选择重复的行

例如,对于人,谁拥有相同的姓氏,我尝试这样做:

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

这工作看起来,我的WPF DataGrid中包含此命令后的行...它最终只显示空行,因为没有列填充值。

或者我试图与人,谁具有相同的城市:

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

有没有做到这一点任何适当的方式?

+0

我不确定被问到的问题。澄清,第一个代码示例工作,但第二个示例不? – Bryan 2012-02-10 16:58:56

+0

两者都不起作用,因为第一个只返回空行(但它返回一些,至少...),第二个不返回 – SeToY 2012-02-10 16:59:40

+1

所以这意味着您的数据库中有多个包含SurName空值的行?看起来他们都在工作,只是没有返回你期望的数据。这将有助于查看“地址”和“人”的类定义。 – Bryan 2012-02-10 17:01:34

回答

9

您只选择在你的榜样关键:

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

我假设你正在尝试做的是选择整行:

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

比较姓和名:

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

编辑:对于L2E,你可以(我认为)使用匿名类型:

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

以上可能是不正确的 - 不是100%确定。

+0

谢谢,我相信这是有效的......我应该如何修改查询以便不仅比较SurNames,而且ForeNames也是如此? .GroupBy(a => a.ForeName,a.SurName)不起作用。 – SeToY 2012-02-10 17:37:43

+0

你的意思是“显示匹配名字和姓氏的行”?看我的编辑。 – 2012-02-10 17:39:51

+0

是的,名字和姓氏相同的行 – SeToY 2012-02-10 17:40:19