【发布时间】:2016-02-12 15:13:44
【问题描述】:
基本上我要做的是让父母按 Parent.type 分组,他们的 Child.type 的状态为“y”,按 child.Date 排序
作为一个例子,我创建了这些类:
public class Collection
{
public IEnumerable<Parent> Parents { get; set; }
public int Id { get; set; }
}
public class Parent
{
public int Id { get; set; }
public Type type { get; set; }
public IEnumerable<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public Status Status { get; set; }
public DateTime Date { get; set; }
}
public enum Type
{
a,
b
}
public enum Status
{
x,
y
}
我想要的是每个类型的父母列表,其中孩子的日期价值最高。
为了让这个例子顺利进行,我添加了一些测试数据:
Collection collection= new Collection
{
Id = 1,
Parents = new List<Parent>
{
new Parent
{
Id= 1,
type = Type.a,
Children = new List<Child>
{
new Child
{
Id = 1,
Status = Status.y,
Date = DateTime.Now.AddDays(-1)
},
new Child
{
Id = 2,
Status = Status.x,
Date = DateTime.Now.AddDays(-1)
}
}
},
new Parent
{
Id= 2,
type = Type.b,
Children = new List<Child>
{
new Child
{
Id = 3,
Status = Status.y,
Date = DateTime.Now.AddDays(-2)
},
new Child
{
Id = 4,
Status = Status.x,
Date = DateTime.Now.AddDays(-2)
}
}
},
new Parent
{
Id= 3,
type = Type.a,
Children = new List<Child>
{
new Child
{
Id = 5,
Status = Status.y,
Date = DateTime.Now.AddDays(-3)
}
}
},
new Parent
{
Id= 4,
type = Type.b,
Children = new List<Child>
{
new Child
{
Id = 6,
Status = Status.y,
Date = DateTime.Now.AddDays(-3)
},
new Child
{
Id = 7,
Status = Status.y,
Date = DateTime.Now.AddDays(-4)
},
new Child
{
Id = 8,
Status = Status.x,
Date = DateTime.Now.AddDays(-4)
}
}
},
}
};
选择的结果应该是一个包含 2 个父级的列表。每种类型( a 和 b )一个。这两个仍然包含它们的所有 Child 对象。
有什么简单的解决办法吗?
我尝试了类似的方法:
List<Parent> test = collection.Parents
.GroupBy(m => m.type)
.Select(
m => m.OrderByDescending(
mm => mm.Children.Select(
r => r).OrderByDescending(
r => r.Date)).FirstOrDefault()).ToList();
但结果并不好。
=====更新=====
感谢 Enigmativity 的例子,这个问题得到了解决。我对 linq 查询做了一些修改,因为我使用的原始内容是由实体框架 (6) 提供的。这对我来说意味着所选的父对象不包含任何子对象,因此我必须选择新的对象类型(因为我们无法实例化实体框架模型提供的类型的新对象)。我的父母也在另一个 IEnumerable 中,所以我也必须在父母上使用 SelectMany。
这导致了这样的事情:(但这不适用于测试类)
var result =
collection
.SelectMany(c => c.Parents)
.GroupBy(p => p.type)
.SelectMany(gps =>
gps
.SelectMany(
gp => gp.Children.Where(c => c.Status == Status.y),
(gp, c) => new { gp, c })
.OrderByDescending(gpc => gpc.c.Date)
.Take(1)
.Select(gpc => new ParentData {Id = gpc.gp.Id, Children= gpc.gp.Children}))
.ToList();
【问题讨论】:
-
干得好,这么新,用可编译的代码问了这么详细的问题。两次快速复制和粘贴,我就能够运行您的代码。我希望更多的新用户也一样好。