有2个列表,我想用C#来获取每个CertID缺少的propId的列表。
list1 CertID , PropID 10,1 11,3
list2 propId, Name 1,Prop1 2,Prop2 3,Prop3。
结果列表 CertId, PropId 10,2 10,3 11,1 11,2
var rows = list1.Where(ra => !List2.AsEnumerable().Any(rb => rb.Propid == ra.propid)).tolist();
你可以使用 选择多个 来扁平化整个列表,就像下面的代码。
var result = list1
.SelectMany(x => list2
.Where(y => y.PropId != x.PropId)
.Select(y => new Test { CertId = x.CertId, PropId = y.PropId }))
.ToList();
用于测试。
1 - 类。
public class Test
{
public int CertId { get; set; }
public int PropId { get; set; }
}
public class Prop
{
public int PropId { get; set; }
public string Name { get; set; }
}
2 - 集合的初始化:
List<Test> list1 = new List<Test>
{
new Test{CertId=10,PropId=1},
new Test{CertId=11,PropId=3},
};
List<Prop> list2 = new List<Prop>
{
new Prop{PropId=1,Name="prop1"},
new Prop{PropId=2,Name="prop2"},
new Prop{PropId=3,Name="prop3"},
};
3 - 查询:
var result = list1
.SelectMany(x => list2
.Where(y => y.PropId != x.PropId)
.Select(y => new Test { CertId = x.CertId, PropId = y.PropId }))
.ToList();
4 - 演示。
foreach(Test test in result)
{
Console.WriteLine($"CertId : {test.CertId}, PropId : {test.PropId}");
}
5 - 结果。
CertId : 10, PropId : 2
CertId : 10, PropId : 3
CertId : 11, PropId : 1
CertId : 11, PropId : 2
希望对你有所帮助。
对于你的问题,我看到的最简单的方法是计算项目的卡提斯乘积,然后找出差异(例如用tuple,我不知道你在列表中使用的是哪种类型)。
// Your Data
var list1 = new List<Tuple<int, int>>
{
new Tuple<int, int>(10,1),
new Tuple<int, int>(11,3),
};
var list2 = new List<Tuple<int, string>>
{
new Tuple<int, string>(1, "Prop1"),
new Tuple<int, string>(2, "Prop2"),
new Tuple<int, string>(3, "Prop3")
};
// Find the certIds and propIds, you might already have them from another source
var certIds = list1.Select(x => x.Item1);
var propIds = list2.Select(x => x.Item1);
// Create cartesian product of certId x propId
var possibilities =
from cert in certIds
from prop in propIds
select new Tuple<int, int>(cert, prop);
// Find the difference between these possibilities and what you have currently
var missing = possibilities.Except(list1);
// Example display
foreach (var miss in missing)
{
Console.WriteLine($"{miss.Item1},{miss.Item2}");
}
Console.ReadKey();
你可以做一个交叉连接,然后过滤不等式。
var results = (
from l1 in list1
from l2 in list2
where l1.PropId != l2.PropId
select new { l1.CertId, l2.PropId }
).ToList();
不幸的是,LINQ只允许在连接语句的 "on "操作中使用 "equals"。 所以你不能使用这个。