LINQ(语言集成查询)提供了一个多功能工具集,可以以简洁高效的方式查询数据。一个常见的场景涉及识别一个列表中存在但在另一个列表中不存在的项。
考虑以下代码片段:
<code class="language-csharp">class Program { static void Main(string[] args) { List<Person> peopleList1 = new List<Person>(); peopleList1.Add(new Person() { ID = 1 }); peopleList1.Add(new Person() { ID = 2 }); peopleList1.Add(new Person() { ID = 3 }); List<Person> peopleList2 = new List<Person>(); peopleList2.Add(new Person() { ID = 1 }); peopleList2.Add(new Person() { ID = 2 }); peopleList2.Add(new Person() { ID = 3 }); peopleList2.Add(new Person() { ID = 4 }); peopleList2.Add(new Person() { ID = 5 }); } } class Person { public int ID { get; set; } }</code>
问题陈述: 给定两个列表,peopleList1 和 peopleList2,编写一个LINQ查询以确定 peopleList2 中存在但在 peopleList1 中不存在的唯一人员。在本例中,期望的结果是 ID 为 4 和 ID 为 5 的人员。
LINQ解决方案: 以下LINQ查询有效地解决了这个问题:
<code class="language-csharp">var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID));</code>
此查询使用 Where() 方法,该方法根据指定的条件过滤 peopleList2 中的项。在这种情况下,条件检查 peopleList1 中的任何项是否具有与 peopleList2 中当前项匹配的 ID。如果没有找到(!peopleList1.Any() == true),则该项包含在结果集中。
替代表达式: 或者,查询可以表示如下:
<code class="language-csharp">var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID));</code>
此变体使用 All() 方法来评估 peopleList1 中的所有项的 ID 是否都与 peopleList2 中的当前项不同。如果此条件成立 (peopleList1.All() == true),则该项包含在结果集中。
注意事项: 务必注意,这两种方法的计算复杂度均为 O(n*m),其中 n 表示 peopleList1 中的项数,m 表示 peopleList2 中的项数。这意味着对于大型数据集,此操作可能会变慢。如果性能是一个问题,请考虑其他方法,例如哈希表或集合运算。
以上是LINQ 如何有效地识别一个列表中另一个列表中不存在的唯一项目?的详细内容。更多信息请关注PHP中文网其他相关文章!