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();
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With