假设我们在名为A和B的表中有两列。我想在c#中编写一个linq查询,该查询返回的列A刚对应于一个唯一列B的行。
示例1:
A B
1 1
1 2
1 3
2 1
3 1
返回:
A B
2 1
3 1
示例2:
A B
1 1
1 1
2 1
3 1
返回:
A B
1 1
2 1
3 1
在示例2中,列A的值为1,它对应于唯一唯一列B的value(1)。因此,结果中也应该出现1、1。
答案 0 :(得分:0)
这是另一种方式,可能不太有效:
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 :(得分:-1)
这是您的答案,它适用于您编写的两种情况,即使第二列的数字不是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();