Search with Linq

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

Here is what I am 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 200,000 items in my collection, and I call this method very often. Is there a relatively simple and effective way to do this?

+4
source share
5 answers
 var closestRecord = _records.MinBy(rec => Math.Abs(rec.Frame - frameNumber)); 

using MinBy from MoreLINQ .

+5
source

What you can try is to store frames in a data structure, sorted by Frame . Then you can perform a binary search when you need to find the frame closest to a given frame number.

+3
source

I do not know that I would use LINQ for this, at least not with orderby.

 static Record FindClosestRecord(IEnumerable<Record> records, int number) { Record closest = null; int leastDifference = int.MaxValue; foreach (Record record in records) { int difference = Math.Abs(number - record.Frame); if (difference == 0) { return record; // exact match, return early } else if (difference < leastDifference) { leastDifference = difference; closest = record; } } return closest; } 
+1
source

You can combine your statements into one ala:

 var closestRecord = (from rec in _records select new { FrameDiff = Math.Abs(rec.Frame - frameNumber), Record = rec }).OrderBy(x => x.FrameDiff).FirstOrDefault().Record; 
0
source

Maybe you can split your large list of items into 5 to 10 smaller lists that are ordered by their Framediff or something like that?

this way the search is faster if you know which list you need to search

0
source

Source: https://habr.com/ru/post/1311754/


All Articles