Home > Software engineering >  can I get the latest file without calculating LastOrDefault
can I get the latest file without calculating LastOrDefault

Time:02-02

Can I get the latest file within foreach loop without calculating last variable using LastOrDefault ?

I don't want to repeat archive.Entries.OrderBy(x => x.LastWriteTime) 2 times

var last = archive.Entries.OrderBy(x => x.LastWriteTime).LastOrDefault();

        foreach (var entry in archive.Entries.OrderBy(x => x.LastWriteTime))
        {
            Console.WriteLine(entry.Equals(last) ? $"latest file: {entry.Name}" : entry.Name);
        }

CodePudding user response:

Like this? You can break the chain of linq queries at any point and resume in another context.

var ordered = archive.Entries.OrderBy(x => x.LastWriteTime).ToArray(); // ToArray() is necessary to prevent double-enumeration in the case of a Queryable set
var last = ordered.LastOrDefault();

foreach (var entry in ordered)
        {
            Console.WriteLine(entry.Equals(last) ? $"latest file: {entry.Name}" : entry.Name);
        }
  •  Tags:  
  • c#
  • Related