对一个列表进行另一个排序 [英] Sort one list by another
问题描述
我有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.
我想要做的是按照其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.
我一直在阅读有关我可以在Linq.OrderBy子句中用作参数的ICompare的信息,但是我找不到任何简单的示例.
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.
我们非常感谢您的帮助.
Any help is most appreciated.
推荐答案
另一种LINQ方法:
var orderedByIDList = from i in ids
join o in objectsWithIDs
on i equals o.ID
select o;
这篇关于对一个列表进行另一个排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!