c# - 用于在表中查找一对一关系的 Linq 查询
问题描述
假设我们在一个名为 A 和 B 的表中有两列。我想在 c# 中编写一个 linq 查询,它返回 A 列仅对应于一个唯一列 B 的行。
示例 1:
AB
1 1
1 2
1 3
2 1
3 1
返回:
AB
2 1
3 1
示例 2:
AB
1 1
1 1
2 1
3 1
返回: AB
1 1
2 1
3 1
在示例 2 中,A 列的值为 1,它对应于 JUST ONE UNIQUE 列 B 值 (1)。所以在结果中,1, 1 也应该出现。
解决方案
这是另一种方法,可能效率不高:
List<Tuple<int, int>> testData = new List<Tuple<int, int>>();
testData.Add(new Tuple<int, int>(1, 1));
testData.Add(new Tuple<int, int>(1, 2));
testData.Add(new Tuple<int, int>(1, 3));
testData.Add(new Tuple<int, int>(2, 1));
testData.Add(new Tuple<int, int>(3, 1));
List<Tuple<int, int>> result = testData
.Distinct() //remove duplicates
.GroupBy(x => x.Item1) //groups by column A
.Select(x => x.ToList()) //transform into a list of lists
.Where(x => x.Count() == 1) //selects lists that have only one item
.Select(x => x[0]) //flattens the list to a single list
.ToList();
推荐阅读
- c++ - QByteArray 访问和严格别名
- javascript - 抽奖命令,按票收费 discord.js
- web-scraping - “requests.get”不保存有用的 youtube 链接
- javascript - x < 1 和 x <= 0 之间的差异
- node.js - 如何动态修改 XML?
- java - Mockito for Resttemplate 交换方法
- docusignapi - 在信封中使用 PDF FormFields
- javascript - 带有 swiperJS 的标签式滑块
- c - 如何确保我的代码不重复数字?
- c# - 从 .Net 调用本机函数时参数值混乱