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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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());
}

2 Comments

How is it connected with the question "how can I get only the latest document from each document type"?
Ok, so sorry about the answer. The code block returns a list. Line was modified in entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.