将一个数组的顺序与另一个数组匹配 [英] Matching the order of one array to another

查看:128
本文介绍了将一个数组的顺序与另一个数组匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID的整数数组,这些数组的顺序正确.然后,我有一个具有ID属性的无序对象数组.

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.

我想按与int数组的顺序匹配的ID对对象进行排序.

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

类似的东西

newObjectArray = oldObjectArray.MatchOrderBy(IdArray)

最可取的

我觉得我应该可以使用LINQ来完成此任务,但是我还没有找到办法.

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();
    }

推荐答案

暴力实施:

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

但是,这需要为IdArray中的每个项目重复搜索结果,并且不能对具有重复ID的项目进行过于整齐的处理.

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

如果对搜索结果进行ILookup,事情会有所改善,因此,为IdArray中的每个项目获取正确的搜索结果现在是O(1)时间.

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);

现在:

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

这篇关于将一个数组的顺序与另一个数组匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆