C# Lambda Expression Speed

c#, lambda

Solution

Your algorithm is inefficient. If you are doing multiple searches on the same list you need to:

- Sort the list appropriately (by your look up key).

- Use a binary search to find the right record.

Your other option is if memory isn't an issue and you want it to be really fast is to put the records into a `Dictionary<Your_Key,Record>`. That will give you the fastest access after you have it setup.

Problem

I have not used many lambda expressions before and I ran into a case where I thought I could make slick use of one. I have a custom list of ~19,000 records and I need to find out if a record exists or not in the list so instead of writing a bunch of loops or using linq to go through the list I decided to try this: ``` for (int i = MinX; i <= MaxX; ++i) { tempY = MinY; while (tempY <= MaxY) { bool exists = myList.Exists(item => item.XCoord == i && item.YCoord == tempY); ++tempY; } } ``` Only problem is it take ~9 - 11 seconds to execute. Am I doing something wrong is this just a case of where I shouldn't be using an expression like this? Thanks. EDIT: Sorry. I should elaborate. I am creating a list of records with the for and while loop and checking if that record exists in myList. That is the only way I could think of going about it. I will reevaluate it and see what I come with up.

Original source