1

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;
2
  • Create a hashset from ids. Commented May 10, 2022 at 9:25
  • Do you have a typo? Is it clients.Id or item.Id? Commented May 10, 2022 at 9:28

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.