[英]Get items not in list using LINQ
有 2 个列表,我希望能够使用 C# 获取每个 CertID 缺少的 propId 的列表
清单1
CertID、PropID
10,1
11,3
清单2
道具ID,名称
1、道具1
2、道具2
3、道具3
结果列表
CertId、PropId
10,2
10,3
11,1
11,2
var rows = list1.Where(ra => !List2.AsEnumerable().Any(rb => rb.Propid == ra.propid)).tolist();
您可以使用SelectMany来展平整个列表,如以下代码:
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 - collections 的初始化:
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
我希望你觉得这有帮助。
我为您的问题看到的最简单的方法是计算项目的笛卡尔积并找出差异(元组示例,我不知道您在列表中使用哪种类型)
// 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”。 所以你不能使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.