MichaelTaylor3D
MichaelTaylor3D

Reputation: 1665

Matching the order of one array to another

I have an int array of ID's that are ordered properly. Then I have an an array of unordered objects that have ID properties.

I would like to order the objects by ID that match the order of the int array.

Something along the lines of

newObjectArray = oldObjectArray.MatchOrderBy(IdArray)

Would be most desirable

I feel like I should be able to accomplish this using LINQ but I have yet to find a way.

My current method doesn't seem very efficient since it has to query on every iteration of the collection. I suspect that performance can suffer for sufficiently large collections. Which eventually will happen.

Here is my current implementation:

    //this is just dummy data to show you whats going on
    int[] orderedIDs = new int[5] {5534, 5632, 2334, 6622, 2344};
    MemberObject[] searchResults = MyMethodToGetSearchResults();

    MemberObject[] orderedSearchResults = new MemberObject[orderedIDs.Count()];
    for(int i = 0; i < orderedIDs.Count(); i++)
    {
        orderedSearchResults[i] = searchResults
                                                .Select(memberObject => memberObject)
                                                .Where(memberObject => memberObject.id == orderedIDs[i])
                                                .FirstOrDefault();
    }

Upvotes: 3

Views: 1582

Answers (1)

spender
spender

Reputation: 120400

A brute force implementation:

MemberObject[] sortedResults = 
      IdArray.Select(id => searchResults
                           .FirstOrDefault( item => item.id == id ))

However, this requires reiterating searchResults for every item in IdArray and doesn't deal too neatly with items that have duplicate ids.

Things improve if you make an ILookup of your search results, so that grabbing the correct search result for each item in IdArray is now O(1) time.

ILookup<int, MemberObject> resultLookup = searchResults.ToLookup(x => x.id);

Now:

MemberObject[] sortedResults = 
      IdArray.SelectMany(id => resultLookup[id])

Upvotes: 4

Related Questions