LINQ:根据Column-Value选择重复的行

时间:2012-02-10 16:55:23

标签: c# linq entity-framework syntax

我正在尝试在DataGrid中显示那些共享相同列值的行。

例如,对于拥有相同姓氏的人,我试过这个:

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

有没有正确的方法呢?

1 个答案:

答案 0 :(得分: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%肯定。

相关问题