Searching with Linq

Posted by Phil on Stack Overflow See other posts from Stack Overflow or by Phil
Published on 2010-06-03T15:50:32Z Indexed on 2010/06/03 15:54 UTC
Read the original article Hit count: 296

Filed under:
|
|
|
|

I have a collection of objects, each with an int Frame property. Given an int, I want to find the object in the collection that has the closest Frame.

Here is what I'm doing so far:

public static void Search(int frameNumber)
{
    var differences = (from rec in _records
                       select new { FrameDiff = Math.Abs(rec.Frame - frameNumber), Record = rec }).OrderBy(x => x.FrameDiff);

    var closestRecord = differences.FirstOrDefault().Record;

    //continue work...
}

This is great and everything, except there are 200,000 items in my collection and I call this method very frequently. Is there a relatively easy, more efficient way to do this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ