我正在尝试按名称对列表进行排序,但是当我得到一个ID时,我不知道该怎么做。例如:
public class CustomTask {
int categoryid;
}
public class DataOption {
int id;
string name;
}
public void Sort() {
List<DataOption> TheListContainingTheCategories = ...;
// The List containing my CustomTasks
List<CustomTask> listTempTasks = ...
var listTasksSorted = listTempTasks.OrderBy(...).ToList();
}
对ID进行排序并不是很难,但是当我想按名称对它进行排序时,我该怎么做呢?
感谢您的帮助
答案 0 :(得分:1)
猜猜最简单的方法是
var listTasksSorted = from ct in listTempTasks
join d in TheListContainingTheCategories on ct.categoryid equals d.id
orderby d.name
select new {ct, d};
然后listTasksSorted
看起来像这样
所以列表按名称排序,ID在一起,不需要额外的功能或成员
替代方案
var listTasksSortedAlternative = TheListContainingTheCategories.Where(d =>
listTempTasks.Any(ct =>
d.id == ct.categoryid)).OrderBy(d => d.name);
看起来像
答案 1 :(得分:0)
试试这个:
public void Sort()
{
List<DataOption> TheListContainingTheCategories = ...;
Dictionary<int, string> lookup = TheListContainingTheCategories.ToDictionary(x => x.id, x => x.name);
List<CustomTask> listTempTasks = new List<CustomTask>();
var listTasksSorted = listTempTasks.OrderBy(c => lookup[c.categoryid]).ToList();
}
假设你想按匹配的
排序当DataOption.id == CustomTask.categoryId 时,DataOption.name