Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching with Linq

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?

like image 245
Phil Avatar asked Jan 21 '23 23:01

Phil


1 Answers

var closestRecord = _records.MinBy(rec => Math.Abs(rec.Frame - frameNumber));

using MinBy from MoreLINQ.

like image 133
dtb Avatar answered Jan 29 '23 08:01

dtb