在 select 查询中扩展现有(匿名)类型
Extend an existing (anonymous) type in a select query
在使用 LinqPad 时,我有一个 Select x, Extra=f(y)
查询,我想 return x
的所有属性(和字段)与 [=13] 处于同一级别=],而不是单独的 x
和 Extra
属性(或字段)。
这可以做到吗?
即我想要 Select x.p1, x.p2, Extra=f(y)
而不必输入那么多内容。
请注意 x
的类型实际上可能是也可能不是匿名的,只是有点不透明或太大而无法手动复制。 VB.NET 隐式类型和 C# 显式 new {}
产生的类型是匿名的。
Jon Skeet 已经否定地回答了这个问题here(但是这个问题不是重复的,因为它是一个特例)。
这里的解决方法是 My Extensions
至少列出准备好粘贴回 Select
查询的属性和字段。
// 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)):"";
}
你可能足够幸运,只能说 Select x.AllProperties("x") Take 1
但是当你需要避免 Linq-to-SQL 妨碍你需要添加更多内容时:(from ... Select x).First().AllProperties("x")
,如果您需要同时获取属性和字段(正如我发现您对 LinqPad 生成的实体所做的那样),则需要更多的箍。
这些将生成类似于 "x.p1, x.p2"
的字符串,可以将其粘贴回原始 Select
查询。
在使用 LinqPad 时,我有一个 Select x, Extra=f(y)
查询,我想 return x
的所有属性(和字段)与 [=13] 处于同一级别=],而不是单独的 x
和 Extra
属性(或字段)。
这可以做到吗?
即我想要 Select x.p1, x.p2, Extra=f(y)
而不必输入那么多内容。
请注意 x
的类型实际上可能是也可能不是匿名的,只是有点不透明或太大而无法手动复制。 VB.NET 隐式类型和 C# 显式 new {}
产生的类型是匿名的。
Jon Skeet 已经否定地回答了这个问题here(但是这个问题不是重复的,因为它是一个特例)。
这里的解决方法是 My Extensions
至少列出准备好粘贴回 Select
查询的属性和字段。
// 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)):"";
}
你可能足够幸运,只能说 Select x.AllProperties("x") Take 1
但是当你需要避免 Linq-to-SQL 妨碍你需要添加更多内容时:(from ... Select x).First().AllProperties("x")
,如果您需要同时获取属性和字段(正如我发现您对 LinqPad 生成的实体所做的那样),则需要更多的箍。
这些将生成类似于 "x.p1, x.p2"
的字符串,可以将其粘贴回原始 Select
查询。