使用LINQ连接两个List按Barcode分组取价格去重计数(交集)的实现方法
问题描述
需要将两个List按Barcode关联分组,统计各Barcode下reducedPrice、ItemPrice的去重值计数,仅保留交集范围内的Barcode数据,不纳入List2独有的条码(比如003、004、005)。
你当前尝试的实现代码如下:
var sameJanWithDiffPriceList3 = (from item in list1 join t in list2 on item.BarcodeNo equals t.BarcodeNo group item by item.BarcodeNo into grp select new { BarcodeNo = grp.Key, ReducedPrice = grp.Select(x => x.ReducedPrice).Distinct().Count(), ItemPrice = grp.Select(x => x.ItemPrice).Distinct().Count() }).ToList();
测试数据
List 1
| Barcode | reducedPrice | ItemPrice |
|---|---|---|
| 000 | 100 | 120 |
| 000 | 320 | 420 |
| 001 | 200 | 360 |
| 001 | 400 | 860 |
| 002 | 120 | 160 |
| 099 | 120 | 160 |
List 2
| Barcode | reducedPrice | ItemPrice | ItemCode |
|---|---|---|---|
| 000 | 100 | 120 | 00 |
| 001 | 200 | 360 | 01 |
| 002 | 120 | 160 | 02 |
| 003 | 120 | 160 | 02 |
| 004 | 120 | 160 | 02 |
| 005 | 120 | 160 | 02 |
期望结果
| Barcode | Count(DistinctReducedPrice) | Count(DistinctItemPrice) |
|---|---|---|
| 000 | 2 | 2 |
| 001 | 3 | 3 |
| 002 | 1 | 1 |
| 099 | 1 | 1 |
当前实现的实际运行结果
| Barcode | Count(DistinctReducedPrice) | Count(DistinctItemPrice) |
|---|---|---|
| 000 | 2 | 2 |
| 001 | 2 | 2 |
| 002 | 1 | 1 |
| 099 | 1 | 1 |
当前实现的统计值和预期存在偏差,需要修正逻辑。
问题根因
- 普通内连接的特性是仅返回两个列表中Barcode能完全匹配的条目,不会保留List1独有的099条码数据——如果你的实际运行结果里出现了099,说明实际执行的代码不是纯内连接,而是做了全量取数或左连接。
- 当前分组逻辑只统计了List1单表内的价格去重值,没有合并同Barcode下List2的价格数据,因此001条码的计数和预期的3存在偏差。
- 你担心的List2独有条码(003、004、005),只要以List1为基准做关联,这些条码因为不存在于List1,根本不会被带入结果,无需额外过滤。
修正后的实现逻辑
如果目标是保留List1所有条目,对每个Barcode合并List1、List2中出现的所有价格值做去重计数,同时完全排除List2独有的条码,可使用如下代码:
var result = list1 // 分组连接:以List1为基准,关联List2中同Barcode的所有条目,保留List1全部数据 .GroupJoin( list2, item => item.BarcodeNo, t => t.BarcodeNo, (item, tGroup) => new { item.BarcodeNo, // 收集当前条目的价格,以及关联到的List2中同Barcode的所有价格 ReducedPrices = new[] { item.ReducedPrice }.Concat(tGroup.Select(x => x.ReducedPrice)), ItemPrices = new[] { item.ItemPrice }.Concat(tGroup.Select(x => x.ItemPrice)) }) // 按Barcode分组,合并同Barcode下的所有价格值 .GroupBy(x => x.BarcodeNo) .Select(grp => new { BarcodeNo = grp.Key, // 去重后计数 DistinctReducedPriceCount = grp.SelectMany(x => x.ReducedPrices).Distinct().Count(), DistinctItemPriceCount = grp.SelectMany(x => x.ItemPrices).Distinct().Count() }) .ToList();
逻辑说明
- 采用
GroupJoin替代普通内连接,既可以保留List1的全部条目(包括List1独有的099条码),又不会把List2独有的003、004、005条码带入结果,满足交集范围的过滤要求 - 统计时会合并同Barcode下两个列表的所有价格值,去重后计数,匹配预期的统计规则
- 代码执行过程中不会出现List2独有的条码数据,无需额外的排除逻辑
内容的提问来源于stack exchange,提问作者ZanZan
相关产品推荐
相关产品推荐

