Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to orderBy Date or find record with oldest date in custom class?

Console App added User class

public class User
{
    public string UserName { get; set; }
    public int Count { get; set; }
    public DateTime LastSeen { get; set; }

    public User(string userName, int count, DateTime lastSeen)
    {
        UserName = userName;
        Count = count;
        LastSeen = lastSeen;
    }
}

So create List of User in Main and populate with entry from console.Read

 static void Main(string[] args)
        {
            List<User> Allusers = new List<User>();

            while (true)
           {
                Console.WriteLine("Please enter name");
                string userName = Console.ReadLine();

                if (userName == "end")
                {
                    break;
                }

                if(Allusers.Count == 0)
                {
                    User newUser = new User(userName, 1, DateTime.UtcNow);
                    Allusers.Add(newUser);
                }
                else if(Allusers.Count < 5)
                {
                    User userExist = Allusers.Find(x => x.UserName == userName);
                    if(userExist != null)
                    {
                        userExist.Count++;
                        userExist.LastSeen = DateTime.UtcNow;
                    }
                    else
                    {
                        User newUser = new User(userName, 1, DateTime.UtcNow);
                        Allusers.Add(newUser);
                    }
                }
                else
                {

//can only hold 5 records
//so here I want to find the record with the earliest date so I can remove it?
How can I do a search or a where or a find?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

where date is the oldest?

order by ascending?

cant find it…

so how do I say

  User oldestUser = Allusers.Find(x => x.LastSeen == //IS OLDEST DATE).firstOrDefault();
Allusers.Remove(oldestUser );

>Solution :

If you are using Linq you could do this: AllUser.OrderByDescending(x => x.LastSeen).First() That will be the first element in the list after ordering descending.

User oldestUser = Allusers.OrderByDescending(x => x.LastSeen).FirstOrDefault();
Allusers.Remove(oldestUser);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading