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

can I get the latest file without calculating LastOrDefault

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);
        }

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

>Solution :

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);
        }
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