-2

Is there a faster alternative to using the Contains method in C#?

Here is a sample that looks like what I'm trying to do, but I have read that Contains is an expensive way to do it and I want to find a better alternative as speed is important.

    public List<Guid> getCumulativeListByUsername(string username)
    {
        List<Guid> CombinedList = new List<Guid>();
        List<Guid> ListA = new List<Guid>();
        List<Guid> ListB = new List<Guid>();

        ListA = getListAFromDatabase(username);
        ListB = getListBFromDatabase(username);

        CombinedList = ListA;

        foreach (Guid x in ListB)
        {
            if (!CombinedList.Contains(x))
            {
                CombinedList.Add(x);
            }
        }
        return CombinedList;
    }

If you could explain your reasoning as well, it would be appreciated.

cmckeeth
  • 95
  • 2
  • 9

1 Answers1

1

Not sure about performance, you'd need to provide details on list length, likely hood of a clash, etc. But you can shorten the code with Linq:

return ListA.Union(ListB).ToList();

I'd want to prove a performance problem exists before trying to arbitrarily improve performance and more than likely making the code less readable.

Andy Lamb
  • 2,151
  • 20
  • 22