1

While working with LinqPad I have a Select x, Extra=f(y) query where I'd like to return all the properties (and fields) of x at the same level as Extra, rather than as separate x and Extra properties (or fields).

Can this be done?

I.e. I want Select x.p1, x.p2, Extra=f(y) without having to type that much.

Note the type of x may or may not actually be anonymous, just somewhat opaque or just too big to copy out manually. The type resulting from the VB.NET implicit typing and the C# explicit new {} is anonymous.

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
  • This question is not so clear even if your answer sheds some light on it. So a new anonymous type with both types as properties is not sufficient? `select new { x, y }` – Tim Schmelter Mar 09 '15 at 07:47
  • @TimSchmelter That is the c# version of my VB.NET example (if you meant `f(y)`, not just `y`). But, yes, I stopped for tea. I should add examples of what I wanted. – Mark Hurd Mar 09 '15 at 08:19

1 Answers1

1

Jon Skeet has already answered this question negatively here (but that question is not a duplicate because it's a special case).

As a workaround here are My Extensions to at least list the properties and fields ready to be pasted back into the Select query.

// Properties so you can "extend" anonymous types
public static string AllProperties<T>(this T obj, string VarName)
{
    var ps=typeof(T).GetProperties();
    return ps.Any()?(VarName + "." + string.Join(", " + VarName + ".", from p in ps select p.Name)):"";
}

// Fields so you can "extend" anonymous types
public static string AllFields<T>(this T obj, string VarName)
{
    var fs=typeof(T).GetFields();
    return fs.Any()?(VarName + "." + string.Join(", " + VarName + ".", from f in fs select f.Name)):"";
}

You may be lucky enough to just be able to say Select x.AllProperties("x") Take 1 but when you need to avoid Linq-to-SQL getting in the way you need to add more: (from ... Select x).First().AllProperties("x"), with even more hoops if you need to get both properties and fields (as I found you do with the entities generated by LinqPad).

These will produce a string like "x.p1, x.p2" that can be pasted back into the original Select query.

Community
  • 1
  • 1
Mark Hurd
  • 10,665
  • 10
  • 68
  • 101