我必须使用以下逻辑通过承包商名称订购以下内容:首先是父母跟随其子女的列。
例如,在图片中,我想要这个结果:
到目前为止,我已经尝试了类似的东西,我确信这种方法不正确,并且仍然不能满足所有情况。
.AsEnumerable().OrderBy(x => x.ContractorName.Split(' ').First()).ThenBy(p=>p.ParentName).ToList<ContractModel.providers>()
答案 0 :(得分:1)
要获得所需内容,您需要执行以下操作:
.AsEnumerable()
.Where(p => p.IsParent)
.OrderBy(p => p.ContractorName)
.SelectMany(p =>
{
// You will return this list
var list = new List<YourType>();
// First you add the parent
list.Add(p);
// Then you add all the children ordered by name
// (I assume you can get them via a relation)
list.AddRange(p.Children.OrderBy(c => c.ContractorName).ToList());
// Finally you return the list
return list;
}).ToList();
这里的逻辑是首先提取父母的记录,然后连接他的所有孩子。 SelectMany
将诀窍返回List
。
答案 1 :(得分:0)
创建CompareTo方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Contractors> contractors = new List<Contractors>() {
new Contractors() { ContractorName = "Panhandle Mental Health Center - Sidney", ParentName = "Panhandle Mental Health Ctr/Region 1"},
new Contractors() { ContractorName = "Panhandle Mental Health Center - Sidney", ParentName = "Panhandle Mental Health Ctr/Region 1"},
new Contractors() { ContractorName = "Panhandle Mental Health Ctr/Region 1"},
new Contractors() { ContractorName = "Region 1 - Panhandle Prevention Coalition", ParentName = "Panhandle Mental Health Ctr/Region 1"},
new Contractors() { ContractorName = "Region 1 Behavioral Health - Ave. D. Scottsbluff",ParentName = "Region 1 Behaviorial Health Authority"},
new Contractors() { ContractorName = "Region 1 Behavioral Health Authority"},
new Contractors() { ContractorName = "Region 1 Behavioral Health Authority - 16 St Scottsbluff", ParentName = "Region 1 Behaviorial Health Authority"},
};
contractors.Sort((x,y) => x.CompareTo(y));
}
}
public class Contractors : IComparable< Contractors>
{
public string ContractorName { get; set; }
public string ParentName { get; set; }
public int CompareTo(Contractors contractor)
{
if (this.ContractorName == null || this.ContractorName.CompareTo(contractor.ContractorName) == 1)
return 1;
if (contractor.ContractorName == null || this.ContractorName.CompareTo(contractor.ContractorName) == -1)
return -1;
if (this.ParentName == null || this.ParentName.CompareTo(contractor.ParentName) == 1)
return 1;
if (this.ParentName == null || this.ParentName.CompareTo(contractor.ParentName) == -1)
return -1;
return 0;
}
}
}