我有一个客户列表,我需要根据业务规则对列表进行排序和分组。
以下是实体。
public class Customer
{
public string FirstName {get; set;}
public string LastName {get; set;}
public DateTime DateofBirth {get; set;}
}
提前致谢。
customers.GroupBy(c => c.FirstName)
.Select(c => c.OrderBy(c => c.FirstName).ThenBy(c => c.LastName));
答案 0 :(得分:2)
您的业务规则有些矛盾:
Group by Customer Name
表示您不会在结果列表中出现多次相同名称。然而你的第三条规则是if there are several results for the same name, then they need to sorted by date of birth
。因此,如果通过在规则#1中进行分组,则意味着排序,您的查询将仅仅是:
customers.OrderBy(c => c.FirstName).
ThenBy(c => c.LastName).
ThenBy(c => c.DateofBirth);
如果您实际上是指分组,则规则#3成为选择组中元素的标准 - 在这种情况下,将为每个组选择最早的客户:
customers.GroupBy(c => c.FirstName + c.LastName).
Select(g => g.OrderBy(c => c.DateofBirth).FirstOrDefault()).
OrderBy(c => c.FirstName).
ThenBy(c => c.LastName);
答案 1 :(得分:2)
对客户名称进行分组似乎有点奇怪,但这样做
var groups = from c in customers
let name = c.FirstName + " " + c.LastName
orderby name ascending, c.DateofBirth ascending
group c by name into g
select g;
答案 2 :(得分:0)
var sortList = (from c in customers
group c by new
{
c.FirstName,
c.LastName,
c.DateofBirth
} into g
select new Customer()
{
FirstName = g.Key.FirstName,
LastName = g.Key.LastName,
DateofBirth = g.Key.DateofBirth
}).OrderBy( x => x.FirstName )
.ThenBy( x=> x.LastName)
.ThenBy(x=> x.DateofBirth);