简体   繁体   中英

C# - Optimizing finding elements in a list by comparing with array

I have a list containing some objects and an string array. I would like to optimize this code if possible. Currently, the Big O notation is O(n^2)

The simplified version of the code:

        List<Client> clients = new List<Client>();
        // ... fill the 'clients' list

        string[] ids = File.ReadAllLines("ids.txt");

        List<Client> result = new List<Client>();
        for (int i = 0; i < ids.Length; i++)
        {
            foreach (var item in clients)
            {
                if (clients.Id == ids[i])
                {
                    result.Add(item);
                    break;
                }
            }
        }

        return result;

You can use Dictionary

Dictionary<string, Client> clients = new Dictionary<string, Client>();

Use the client's id as a key

Then, just go through the id array in one loop and retrieve clients.

You can use LINQ like this:

    string[] ids = File.ReadAllLines("ids.txt");

    List<Client> result = clients.Where(x => ids.Contains(x.Id)).ToList();

    return result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM