Search code examples
c#searchindirection

Search by value of object property in an indirection array


I have an array of Int32, every element contains index of reference to an object in another array:

class MyObject {
    public Int32 Time;
}

MyObject[] _objects;
Int32[] _indices;

Now i need to find index of an object which Time is closest to some Double d. The pseudocode of comparison could be like this:

for (i = 0; i < _indices.Length; i++)
    if (d > _objects[indices[i]].Time)
        ...

I don't want to write algorithm by hands. Can i somehow use one of standard library algorithms?

EDIT:

I think it is important to say, that _indices stores indexes of objects in order of increasing .Time.


Solution

  • You could use this LINQ query:

    int indexClosestTime = indices
        .Select(i => new { Object = _objects[i], Index = i})
        .OrderBy(x => Math.Abs(d - x.Object.Time))
        .First().Index;
    

    I have used Math.Abs, so it doesn't mater if the Time is smaller or greater than d. You wasn't clear regarding this. It also only returns one index even if there are multiple with the same distance.