2

I have a class that is like this:

class DateTimeProperty
{
   public string Id { get; set; }
   public DateTime TDateTime { get; set; }
}

and I use it like so:

List<DateTimeProperty> dtp = new List<DateTimeProperty>();

and I fill the list like so:

var item = new DateTimeProperty
{
   Id = id,
   TDateTime = transactioDateTime
};
dtp.Add(item);

Then I get the maximum date like so

maxDate = dtp.Max(x => x.TDateTime);

but what I need is the Id that has that date. Can you please show me how to get this? The whole code is below:

static void Main(string[] args)
{
    List<DateTimeProperty> dtp = new List<DateTimeProperty>();
    var format = "dd/MM/yyyy HH:mm:ss.fff";
    var folderPath = @"I:\LCS Transactions";
    DirectoryInfo di = new DirectoryInfo(folderPath);
    List<DateTime> dateTimeArray = new List<DateTime>();
    DateTime maxDate;
    FileInfo[] fi = di.GetFiles();

    foreach(FileInfo f in fi)
    {
        var file = GetHeader(f.FullName);

        if (!file.Contains(".txt"))
        {
            if (file.Contains("_"))
            {
                var spike = file.Split('_');
                var transactionType = spike[0];
                var dateTime = spike[3];
                var id = spike[4];
                var year = dateTime.Substring(0, 4);
                var month = dateTime.Substring(4, 2);
                var day = dateTime.Substring(6,2);
                var hour = dateTime.Substring(8, 2);
                var minute = dateTime.Substring(10, 2);
                var seconds = dateTime.Substring(12, 2);
                var miiliseconds = dateTime.Substring(14, 3);
                var stringDate = $@"{day}/{month}/{year} {hour}:{minute}:{seconds}.{miiliseconds}";

                DateTime transactioDateTime = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);

                var item = new DateTimeProperty
                {
                    Id = id,
                    TDateTime = transactioDateTime
                };

                Console.WriteLine(transactioDateTime);

                //dateTimeArray.Add(transactioDateTime);
                dtp.Add(item);
            }
        }
    }

            maxDate = dtp.Max(x => x.TDateTime);
            Console.WriteLine("=====================");
            Console.WriteLine(maxDate);

            Console.ReadLine();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

3 Answers3

4

You can just use OrderByDescending, then FirstOrDefault

var result = dtp.OrderByDescending(x => TDateTime).FirstOrDefault();

if(result != null)
   Console.WriteLine(result.Id);

Additional Resources

Enumerable.OrderByDescending Method

Sorts the elements of a sequence in descending order.

Enumerable.FirstOrDefault Method

Returns the first element of a sequence, or a default value if no element is found.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
3

Just order by the date and take the Id property from the first item:

var maxDateId = dtp
    .OrderByDescending(x => x.TDateTime)
    .FirstOrDefault()?.Id;

FirstOrDefault can return null if the sequence is empty, which is why I use the null conditional operator (?.) to access the Id property. If the sequence is empty, maxDateId will be null, so you might have to check for this to make your code safe from a NullReferenceException.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
1

You can avoid paying the performance price of sorting the list by using the LINQ Aggregate method.

var maxDateItem = dtp.Aggregate((DateTimeProperty)null, (max, item) =>
{
    return max == null || item.TDateTime > max.TDateTime ? item : max;
});
var maxDateItemId = maxDateItem.Id; // Will throw if the list has no elements

Update. More solutions here: How to use LINQ to select object with minimum or maximum property value.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104