[英]Linq query for finding one-to-one relation inside a table
假设我们在名为 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,它对应于仅一个唯一的 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();
这是给你的答案,它适用于你写的两种情况,即使第二列的数字不是 1 但它是唯一的:
List<Tuple<int, int>> testData = new List<Tuple<int, int>>
{
new Tuple<int, int>(1, 1),
new Tuple<int, int>(1, 1),
new Tuple<int, int>(1, 1),
new Tuple<int, int>(2, 1),
new Tuple<int, int>(3, 1),
new Tuple<int, int>(4, 2),
new Tuple<int, int>(4, 2)
};
var filteredData = testData
.GroupBy(l => l.Item1)
.Select(g => new
{
Item1 = g.Key,
Count = g.Select(l => l.Item2).Distinct().Count()
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.