With linq i can create a query like this
XElement.Elements("...").Select(x=> useX(x));
now as x creates only a wrapper Action and useX's parameter is XElement you can use it like this aswell:
XElement.Elements("...").Select(useX);
However when i have a type that has a constructor with a matching type i.e. MyClass(XElement element) i have to use:
XElement.Elements("...").Select(x=> new MyClass(x));
My question: Is there any way to shorten the construction of an object in a way like above but with a constructor? I imagined something like this:
XElement.Elements("...").Select(MyClass);
Is there any way to shorten the construction of an object in a way like above but with a constructor
Short answer: No, there is not.
Longer "answer" (not actually an answer, more a workaround if you want it):
You can add a static construction method to MyClass
:
public class MyClass
{
public MyClass(XElement elem)
{
// your constructor logic
}
public static MyClass Create(XElement elem)
{
return new MyClass(elem);
}
}
and use that
XElement.Elements("...").Select(MyClass.Create);
But whether it's worth it is up to you! (Personal opinion: It's not worth it, just stick with new MyClass(x)
)
No, you can't shorten a call to a constructor inside a lambda expression. The problem is that a constructor is called from an operation with new new
operator.
You are stuck with .Select(x=> new MyClass(x))
. Of course, you can make a factory method to call instead, but that is more like a workaround.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With