我有一个名为jobList的自定义对象列表。该列表有很多字段,但我想按两个字段排序,FolderID和JobName。该列表如下所示:
job.FolderID = 3
job.JobName = "oper01_quick"
job.FolderID = 3
Job.JobName = "oper02_quick"
job.FolderID = 1
job.JobName = "min01_selfie"
job.FolderID = 2
job.JobName = "max01_experion"
job.FolderID = 2
job.JobName = "max02_experion"
我想对此列表进行排序,使其显示如下:
job.FolderID = 1
job.JobName = "min01_selfie"
job.FolderID = 2
job.JobName = "max01_experion"
job.FolderID = 2
job.JobName = "max02_experion"
job.FolderID = 3
job.JobName = "oper01_quick"
job.FolderID = 3
Job.JobName = "oper02_quick"
我想如果我做了这个LINQ OrderBy,那么:
jobList.OrderBy(j => j.FolderID).ThenBy(j => j.JobName);
它会实现这一目标。但事实并非如此。它使订单看起来像这样:
job.FolderID = 1
job.JobName = "min01_selfie"
job.FolderID = 2
job.JobName = "max01_experion"
job.FolderID = 3
job.JobName = "oper01_quick"
job.FolderID = 2
job.JobName = "max02_experion"
job.FolderID = 3
Job.JobName = "oper02_quick"
任何人都可以帮我订购正确的清单吗?
谢谢,
Chewdoggie
答案 0 :(得分:2)
你在如何进行排序方面是正确的,但是你需要将它分配给变量以获得生成的排序集合:
请参阅.NET小提琴:http://dotnetfiddle.net/wISQVv
这基本上就是它的作用:
var sortedJobs = jobs.OrderBy(j => j.FolderID).ThenBy(j => j.JobName);
foreach(var job in sortedJobs){
Console.WriteLine(job.FolderID + " " + job.JobName);
}
答案 1 :(得分:1)
我只能看到一种可能的扩展:您没有将OrderBy
/ ThenBy
结果分配回源变量。
这些方法(以及整个LINQ)不会更改源集合。而不是那样,他们创建了具有排序元素的新集合。这就是你必须分配回来的原因:
jobList = jobList.OrderBy(j => j.FolderID).ThenBy(j => j.JobName).ToList();
要对列表进行排序,您必须使用Sort
方法,使用自定义比较器:
public class JobComparer : IComparer<Job>
{
public int Compare(Job x, Job y)
{
var folderDifference = x.FolderId.CompareTo(y.FolderId);
return folderDifference == 0 ? x.JobName.CompareTo(y.JobName) : folderDifference;
}
}
jobList.Sort(new JobComparer());
答案 2 :(得分:0)
jobs.OrderBy(j => j.JobName).OrderBy(j => j.FolderId)
似乎工作正常。
答案 3 :(得分:0)
如果您的Job
课程如下:
public class Job
{
public int FolderId { get; set; }
public string JobName { get; set; }
}
然后实施IComparer<T>
:
public class JobComparer : IComparer<Job>
{
public int Compare(Job x, Job y)
{
if (x.FolderId != y.FolderId) return x.FolderId.CompareTo(y.FolderId);
return x.JobName.CompareTo(y.JobName);
}
}
并使用它:
var orderedList = items.OrderBy(x => x, new JobComparer()).ToList();
这应该给出您期望的结果。这是LINQPad
中的输出: