Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Short constructor as action

Tags:

c#

linq

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);
like image 788
ShinuSha Avatar asked Dec 19 '22 01:12

ShinuSha


2 Answers

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

like image 173
Jamiec Avatar answered Dec 30 '22 05:12

Jamiec


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.

like image 28
Patrick Hofman Avatar answered Dec 30 '22 04:12

Patrick Hofman