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

Create LINQ intermediate variable the way .Select it does

I created the following extension:

public static class StackTraceExtensions
{
    public static string Callers(this StackTrace trace)
    {
        return string.Join(" < ", trace.GetFrames().Select(sf => sf.GetMethod().DeclaringType.Name + "." + sf.GetMethod().Name));
    }
}

but calling GetMethod() every time isn’t a good solution. I looked for some way to create an intermediate variable the way the LINQ .Select function it does.

.Select is available only for IEnumerable and is intended for multiple values, therefore I developed yet another extension, this time for any object:

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

public static class ObjectExtensions
{
    public static TResult Self<TSource, TResult>(this TSource source, Func<TSource, TResult> selector) => selector(source);
}

This extension could be used as follows:

public static class StackTraceExtensions
{
    public static string Callers(this StackTrace trace)
    {
        return string.Join(" < ", trace.GetFrames().Select(sf => sf.GetMethod().Self(mb => $"{mb.DeclaringType.Name}.{mb.Name}")));
    }
}

It allows me to deal here with the intermediate mb "variable".

Is there some standard extension that does the same so I don’t need to create my own?

>Solution :

You can first select the method and then use it in a subsequent Select:

return string.Join(" < ", trace.GetFrames()
    .Select(sf => sf.GetMethod())
    .Select(m => $"{m.DeclaringType.Name}.{m.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