首页 > 解决方案 > 用于在表中查找一对一关系的 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 也应该出现。

标签: c#linq

解决方案


这是另一种方法,可能效率不高:

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

推荐阅读