LinQ to get the latest group of records satisfying a condition

时间:2016-07-11 20:16:18

标签: c# linq asp.net-mvc-4

I have below stated 2 tables:

enter image description here

now I want to get the set of Child Table objects for whichever their parent table entries are latest(wr.r.t lastmodified). It should be something like....

List<Child_Table> List = ChildsList.Where(x=>x.name =="pqr" && status == "done")
    .Select(x=>x.Parent.lastmodified == recent record).....ToList();

2 个答案:

答案 0 :(得分:1)

You can use GroupBy on the date, then OrderByDescending on the Key then take the First followed by SelectMany to flatten the results.

var result = ChildsList.Where(x => x.name == "pqr" && x.status == "done")
     .GroupBy(x => x.Parent.lastmodified)
     .OrderByDescending(g => g.Key)
     .First()
     .SelectMany(g => g)
     .ToList();

答案 1 :(得分:0)

You could use a join to accomplish it:

var results = children
    .Join(parents.OrderByDescending(p => p.lastmodified).Take(1),
        c => c.parent_id,
        p => p.id,
        (c, p) => c)
    .Where(x => x.name == "pqr" && x.status == "done")
    .ToList();