IEnumerable.Select() for a single item

  • A+
Category:Languages

I recently created this extension method:

public static TR Calculate<TS, TR>(this TS item, Func<TS, TR> selector)     => selector(item); 

Then, I am able to refactor this ugly code, from:

int value = panel.Controls.Cast<Control>().Last().Location.Y        + panel.Controls.Cast<Control>().Last().Size.Height; 

to:

int value = panel.Controls.Cast<Control>().Last().Calculate(     o => o.Location.Y + o.Size.Height); 

I would like to know if there is a way to do this using built in .NET functions instead?

 


By "innate", I guess you mean you don't want to any new methods yourself?

Well, you can do something like this:

value = ((Func<InputType, OutputType>)(o => o.First + o.Second + o.Property.Value))(collection[calc(param)]); 

Basically, casting the lambda to a delegate type and then calling the delegate.

Or maybe I have overcomplicated this. What you actually want might toto just not write collection[calc(param)] that many times. If that's the case, you can just:

var o = collection[calc(param)]; value = o.First + o.Second + o.Property.Value; 

I don't see why you can't do it like that.

I really suggest you write a separate a method for this kind of transformation. It will be much more readable.

// name this properly so that it describes what you actually want. public OutputType TransformCollectionItem(TInput o) {     return o.First + o.Second + o.Property.Value; }  

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: