我有一个项目对象列表,我想通过使用项目对象中的几个不同字段来对集合进行排序。
IEnumerable<Project> list = GetProjectList();
public class Project
{
public DateTime? Date;
public string ImportanceLevel;
}
我首先要
我很欣赏如果这些是整数值会更好但不幸的是它们现在存储为字符串。)
答案 0 :(得分:3)
一个选项是
var sorted = list.OrderBy(l => l.Date.HasValue ? l.Date : DateTime.MaxValue)
.ThenBy(l => l.ImportanceLevel == "High" ? 1 :
(l.ImportanceLevel == "Medium" ? 2 : 3));
在这里,它会做你想要的,也可以按重要性对日期相同的项目进行排序。
或者,
var sorted2 = list.OrderBy(l => l.Date.HasValue ?
int.Parse(l.Date.Value.ToString("yyyyMMdd")) :
(l.ImportanceLevel == "High" ?
100000001 :
(l.ImportanceLevel == "Medium" ? 100000002 : 100000003)));
在哪里,它不会按重要性对具有日期的项目进行排序。
答案 1 :(得分:1)
//Order by the projects with Date
var projectsWithDate = list.Where(d => d.Date != null)
.OrderBy(s => s.Date).ToList();
// Projects without Dates
var withoutdate = list.Where(d => d.Date == null)
.OrderBy(g =>
{
if (g.ImportanceLevel == "High")
return 1;
if (g.ImportanceLevel == "Medium")
return 2;
if (g.ImportanceLevel == "Low")
return 3;
return 0;
})
.ToList();
//Add the second list to first.
projectsWithDate.AddRange(withoutdate);
//现在你可以使用projectsWithDate集合。
答案 2 :(得分:0)
这将有效
var orderedList = list
.OrderBy(p => p.Date)
.ThenByDescending(p =>
{
if (p.ImportanceLevel == "Low")
return 1;
if (p.ImportanceLevel == "Medium")
return 2;
if (p.ImportanceLevel == "Hight")
return 3;
return 0;
});
答案 3 :(得分:0)
public class Project
{
public DateTime? Date;
public string ImportanceLevel;
}
var sortedProejcts =
projects.OrderByDescending(p => p.Date.HasValue)
.ThenBy(p => Math.Abs(DateTime.Now.CompareTo(p.Date ?? DateTime.MaxValue)))
.ThenByDescending(
p =>
{
switch (p.ImportanceLevel)
{
case "Low":
return 1;
case "Medium":
return 2;
case "High":
return 3;
default:
return 0;
}
});