0

I have a list with objects such as this one:

public class ReportViewModel
{
    public string DocumentName { get; set; } = string.Empty;
    public DateTime? DocumentDate { get; set; }
    public string DocumentTypeName { get; set; } = string.Empty;
}

I want to get distinct list of objects, where I will get the newest document based on the document type, and only get the latest document for each type. The api currently returns list with documents and it might documents from the same document type but from a different date, how can I get only the latest document from each document type?

halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262

2 Answers2

1

You need to use GroupBy and FirstOrDefault together.

Let's say you have

  Name              DocumentDate      DocumentTypeName   
-------------------------------------------------------
 Document A-1        2021-05-01          A          
 Document A-2        2021-04-28          A
 Document B-1        2021-05-01          B          
 Document B-2        2021-04-28          B
 Document C-1        2021-05-01          C          
 Document C-2        2021-04-28          C
 Document C-3        2021-04-25          C

Then what you need to do is

 var groupedList = reportViewModelList.GroupBy(i => i.DocumentTypeName)
                .Select(i => i.OrderByDescending(o => o.DocumentDate).FirstOrDefault());

It gives you the following result as expected.

  Name              DocumentDate      DocumentTypeName   
-------------------------------------------------------
 Document A-1        2021-05-01          A
 Document B-1        2021-05-01          B
 Document C-1        2021-05-01          C

See: How to get first record in each group using Linq

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
0

You can use the following code to distinct elements by last created time:

using (var db = new YourDocumentDbContext())
{
var documents = db.Documents.AsEnumerable().GroupBy(a => a.DocumentTypeName).Select(a => a.OrderByDescending(a=>a.createdTime).FirstOrDefault());
}