c# - 过滤重复行
问题描述
我这里有一段代码:
var grouped = nonGrouped.GroupBy(x => new
{
x.Id,
x.Col1,
x.Col2
}).Select(x => new MyDbTable
{
Id = x.Key.Id,
VALUE = x.Sum(y => y.Value),
Col1 = x.Key.Col1,
Col2 = x.Key.Col2
}).ToList();
//Filter out rows with the same Col1/Col2 combination
var dbTableList = new List<MyDbTable>();
grouped.ForEach(x =>
{
if (!dbTableList.Any(a => a.Col1 == x.Col2 && a.Col2 == x.Col1))
{
dbTableList.Add(x);
}
});
我想删除注释“//过滤出具有相同 Col1/Col2 组合的行”下的代码,并以某种方式将此功能添加到注释上方的我的 LINQ 语句中
解决方案
这应该很适合你:
var dbTableList =
nonGrouped
.GroupBy(x => new
{
x.Id,
x.Col1,
x.Col2
})
.Select(x => new MyDbTable
{
Id = x.Key.Id,
VALUE = x.Sum(y => y.Value),
Col1 = x.Key.Col1,
Col2 = x.Key.Col2
})
.GroupBy(x => new
{
x.Col1,
x.Col2
})
.SelectMany(xs => xs.Take(1))
.ToList();
完成这项工作的关键是GroupBy
//组合SelectMany
。Take(1)
推荐阅读
- python - 如何用python计算文本中所有数字的总和?
- python - 循环遍历一系列文件夹和子文件夹,将特定扩展名的文件复制到目标文件夹中
- python - 我怎样才能让函数/方法根据正在使用的类将密码附加到不同的列表中?
- linux - 本地和 QA 上的 CSV 导出编码不匹配
- python - Python,用于总结的每个句子的词频
- javascript - 如何将包含 json 数据的文本文件转换为订购了所有 json 有效负载的 json 文件?
- r - 有没有办法在 JAGS 中获取和存储矩阵元素的位置?
- python - Scipy.integrate.odeint 在不连续函数上的意外行为
- json - 在 Json 配置命令中添加新行
- linux - 为什么使用部署管理器模板创建资源时不需要服务帐户用户角色(roles/iam.serviceAccountUser)?