Home > Backend Development > C++ > How Can LINQ Efficiently Filter Items in One List Based on the Presence of Items in Another List?

How Can LINQ Efficiently Filter Items in One List Based on the Presence of Items in Another List?

Barbara Streisand
Release: 2025-01-19 18:27:10
Original
308 people have browsed it

How Can LINQ Efficiently Filter Items in One List Based on the Presence of Items in Another List?

Use LINQ query to filter items in the list

LINQ provides an efficient way to filter items in a list based on whether the item exists in another list. Please see the code example below:

class Program
{
    static void Main(string[] args)
    {
        // 示例数据
        List<Person> peopleList1 = new List<Person>() { new Person() { ID = 1 }, new Person() { ID = 2 }, new Person() { ID = 3 } };
        List<Person> peopleList2 = new List<Person>() { new Person() { ID = 1 }, new Person() { ID = 2 }, new Person() { ID = 3 }, new Person() { ID = 4 }, new Person() { ID = 5 } };
    }
}

class Person
{
    public int ID { get; set; }
}
Copy after login

We need to find the items in peopleList2 that are not in peopleList1. This can be achieved via LINQ.

Use the Except() method

LINQ provides the Except() method, which returns all elements in the first list that are not in the second list. We can use it as follows:

var result = peopleList2.Except(peopleList1);
Copy after login

This will return a collection containing people with IDs 4 and 5.

Use LINQ query syntax

LINQ also allows us to perform filtering operations using query syntax. Here's one way to achieve the same result using query syntax:

var result = from p in peopleList2
             where !peopleList1.Any(p2 => p2.ID == p.ID)
             select p;
Copy after login

This query produces the same results as the Except() method.

Performance Description:

It should be noted that the time complexity of both methods is O(n*m), where n and m are the sizes of the two lists being compared. This means that as the size of the list grows, the time required for the filtering operation increases significantly. For large data sets, other methods may need to be explored to optimize performance.

The above is the detailed content of How Can LINQ Efficiently Filter Items in One List Based on the Presence of Items in Another List?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template