[英]Custom Icomparer in Linq to Objects
I have a List. 我有一个清单。
Where T is a class have properties like int and other parameters 其中T是一个类,具有诸如int和其他参数的属性
Eg 例如
ID Name
1 Apple
2 Banana
3 Test
Now i have another List which specify order 现在我有另一个列表指定顺序
Like 2,1,3
So i want to sort them using 2,1,3 like Banana,Apple and then Test 所以我想使用2,1,3(例如Banana,Apple)对它们进行排序,然后进行测试
How can i implement this wihh IComaparer 我该如何实现此功能?
Currently i tries this but it failed 目前,我尝试了这个,但是失败了
test = test.OrderBy(p=> SortableIntList.Contains(p.ID));
To quickly get it working, 为了使其快速生效,
test = test
.Where(p => SortableIntList.Contains(p.ID))
.OrderBy(p => SortableIntList.IndexOf(p.ID));
To make it more efficient, you may want to store your sort order in a dictionary (ID => position) and then call it like 为了提高效率,您可能需要将排序顺序存储在字典中(ID =>位置),然后像这样调用它
var SortableIntDictionary = SortableIntList
.Select((ID, Index) => new { ID, Index })
.ToDictionary(p => p.ID, p => p.Index);
test = test
.Where(p => SortableIntDictionary.ContainsKey(p.ID))
.OrderBy(p => SortableIntDictionary[p.ID]);
Try this, no need for comparer 试试这个,不需要比较器
// Setup test data
var orderList = new List<int> { 2, 1, 3 };
var stuffList = new List<Stuff> {
new Stuff { Id = 1, Name = "Apple" },
new Stuff { Id = 2, Name = "Banana" },
new Stuff { Id = 3, Name = "Test" }
};
// Do sort according to list
var result = orderList.Select(idx => stuffList.Where(s => s.Id == idx));
Edit: It may be faster to create an ID-lookup: 编辑:创建ID查找可能更快:
var stuffDictionary = stuffList.ToDictionary(s => s.ID, s => s);
var result = orderList.Where(idx => stuffDictionary.ContainsKey(idx))
.Select(idx => stuffDictionary[idx]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.