BackDev1001
BackDev1001

Reputation: 11

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;

Upvotes: 1

Views: 286

Answers (2)

Nikola Develops
Nikola Develops

Reputation: 161

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;

Upvotes: 0

Eli Blokh
Eli Blokh

Reputation: 12293

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.

Upvotes: 4

Related Questions