Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order an ICollection [duplicate]

I have a user object with a collection of email. I want to return the last registered address. To do this I made a DataTable, run Select and ordered on date, but is they're any other way of doing this directly with the collection?

So basically what I want is that the address at [0] position is the last registered. Can I achieve this with ICollection or should I use something else?

User:

public ICollection<EmailAddress> EmailAddresses { get; set; } = new HashSet<EmailAddress>();

EmailAddress:

public DateTime DateCreated { get; set; }
public int UserId { get; set; }
public string Address { get; set; }
public DateTime DateLastInvoked { get; set; } = DateTime.Now;
public int LastInvokedByClientId { get; set; }

Solution:

EmailAddress result = this.EmailAddresses.Where(adr => adr.Active.Equals(true)).OrderByDescending(dt => dt.DateCreated).First();
like image 369
SteinTheRuler Avatar asked Mar 08 '23 21:03

SteinTheRuler


2 Answers

Look up LINQ. There are more basic linq query operations.

using System.Linq;

EmailAddresses = EmailAddresses.OrderByDescending(r => r.DateCreated).ToList();

This will order your collection in descending order.

like image 87
jegtugado Avatar answered Mar 19 '23 16:03

jegtugado


If you just want the last registered address, you'd sort the list then use First(), like so:

var lastRegisteredAddress = EmailAddresses.OrderByDescending( a => a.DateCreated ).First();
like image 24
John Wu Avatar answered Mar 19 '23 15:03

John Wu