我在内存中有2个IEnumerable对象集合。
Collection1是一个包含以下内容的列表:
Id, Name, Category etc.
Collection2是一个包含
的列表Id, SortOrder
每个集合中的Id 都有相应的值。
SortOrder 是一个int。
我需要从 Collection2
中 SortOrder 的值对 Collection1 进行排序任何人都知道怎么做?
答案 0 :(得分:1)
您可能只想加入它们并按正确的字段排序
from obj1 in collection1
join obj2 in collection2 on obj1.Id equals obj2.Id
orderby obj2.SortOrder
select obj1
或者,如果像我一样,你更喜欢Lamda语法
var result = collection1.Join(collection2,
a => a.Id,
b => b.Id,
(a, b) => new {Obj1 = a,Obj2 = b})
.OrderBy(x => x.Obj2.SortOrder)
.Select(x => x.Obj1);
没有加入的方法是将Id / Sortorder集合变成字典并查找排序顺序:
var sortOrderDict = collection2.ToDictionary(k => k.Id, v => v.SortOrder);
var result = coll1.OrderBy(x => sortOrderDict[x.Id]);
答案 1 :(得分:0)
static void Main(string[] args)
{
var coll1 = new List<(int Id, string Name, string Category)>
{
(1,"A","AA"),
(2,"B","BB"),
(3,"C","CC"),
(4,"D","DD"),
(5,"E","EE")
};
var coll2 = new List<(int Id, int Order)>
{
(5,1),
(4,2),
(3,3),
(2,4),
(1,5),
(0,6)
};
var sorted = coll1.OrderBy(x => coll2.FirstOrDefault(y => x.Id == y.Id).Order);
foreach (var item in sorted)
Console.WriteLine(item);
}
结果
(5, E, EE)
(4, D, DD)
(3, C, CC)
(2, B, BB)
(1, A, AA)
Press any key to continue . . .
这种优雅的方式你甚至可以洗牌:
var sorted = coll1.OrderBy(_ => Guid.NewGuid());
答案 2 :(得分:-2)
// here sortedlist1 will be sorted
var sortedlist1 = list1.OrderBy(x=>x.id = GetOrder(x.id));
public int Getorder(int id)
{
return list2.Where(x=> x.id ==id).FirstOrDefault().SortedOrder;
}
它对我有用..