另一个排序一架C#列表 [英] Sort one C# list by another

查看:140
本文介绍了另一个排序一架C#列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个列表对象,一个就是整数的列表,另一个是对象的列表但对象有一个ID属性。

I have 2 list objects, one is just a list of ints, the other is a list of objects but the objects has an ID property.

我想要做的排序是在相同的排序为int的名单由它的ID对象的列表。

What i want to do is sort the list of objects by its ID in the same sort order as the list of ints.

我一直玩弄了一会儿现在正试图得到它的工作,到目前为止没有喜悦,

Ive been playing around for a while now trying to get it working, so far no joy,

下面是我迄今为止...

Here is what i have so far...

//**************************
//*** Randomize the list ***
//**************************
if (Session["SearchResultsOrder"] != null)
{
    // save the session as a int list
    List<int> IDList = new List<int>((List<int>)Session["SearchResultsOrder"]);
    // the saved list session exists, make sure the list is orded by this
    foreach(var i in IDList)
    {
        SearchData.ReturnedSearchedMembers.OrderBy(x => x.ID == i);
    }
}
else
{
    // before any sorts randomize the results - this mixes it up a bit as before it would order the results by member registration date                        
    List<Member> RandomList = new List<Member>(SearchData.ReturnedSearchedMembers);
    SearchData.ReturnedSearchedMembers = GloballyAvailableMethods.RandomizeGenericList<Member>(RandomList, RandomList.Count).ToList();

    // save the order of these results so they can be restored back during postback
    List<int> SearchResultsOrder = new List<int>();
    SearchData.ReturnedSearchedMembers.ForEach(x => SearchResultsOrder.Add(x.ID));
    Session["SearchResultsOrder"] = SearchResultsOrder;
}   

这整点是这样当用户搜索的成员,他们最初以随机顺序显示,那如果他们点击第2页,他们仍然在秩序和未来20显示结果。

The whole point of this is so when a user searches for members, initially they display in a random order, then if they click page 2, they remain in that order and the next 20 results display.

我一直在阅读有关ICompare我可以为Linq.OrderBy子句中使用的参数,但我无法找到任何简单的例子。

I have been reading about the ICompare i can use as a parameter in the Linq.OrderBy clause, but i can’t find any simple examples.

我希望一个优雅,很简单的LINQ风格的解决方案,以及我总是希望。

I’m hoping for an elegant, very simple LINQ style solution, well I can always hope.

任何帮助最AP preciated

Any help is most appreciated

Truegilly

Truegilly

推荐答案

另一个LINQ的方法:

Another LINQ-approach:

 var orderedByIDList = from i in ids 
                       join o in objectsWithIDs
                       on i equals o.ID
                       select o;

这篇关于另一个排序一架C#列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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