我有两个对象,我想合并它们:
public class Foo
{
public string Name { get; set; }
}
public class Bar
{
public Guid Id { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public string Property4 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
创造:
public class FooBar
{
public string Name { get; set; }
public Guid Id { get; set; }
public string Property1 { get; set; }
public …Run Code Online (Sandbox Code Playgroud) 我试图在Linq.Expression树中调用String.Format.这是一个简单的例子:
var format = Expression.Constant("({0}) {1}");
var company = Expression.Property(input, membernames.First());
var project = Expression.Property(input, membernames.Last());
var args = new Expression[] {format, company, project};
var invoke = Expression.Call(method,args);
Run Code Online (Sandbox Code Playgroud)
但问题是String.Format的签名是:
String.Format(string format, params object[] args)
Run Code Online (Sandbox Code Playgroud)
而我正试图传递Expression [].
现在我可以解决创建数组的所有麻烦,用表达式的结果填充它,但我真正想要的结果是这样的:
String.Format("({0}) {1}", input.foo, input.bar)
Run Code Online (Sandbox Code Playgroud)
如何通过Linq表达式调用params函数?
你好,
我正在使用LINQ和EF与C#4.0.我已将基本的ELMAH表拖入EF(已构建并保存了很多次).一切都按照人们的预期运作.
但是试图过于雄心勃勃并需要一些帮助 - 我试图从作为变量传入的表达式中获取Column名称.
我想要的是这个:
传入:x => x.ErrorId
得到:"ErrorId"
public void GetColumnName(Expression<Func<T, object>> property)
{
// The parameter passed in x=>x.Message
// Message works fine (probably because its a simple string) using:
string columnName = (property.Body as MemberExpression).Member.Name;
// But if I attempt to use the Guid or the date field then it
// is passed in as x => Convert(x.TimeUtc)
// As a result the above code generates a NullReference exception
// i.e. {"Object reference not set to …Run Code Online (Sandbox Code Playgroud) 我写了一个HtmlHelper表达式,我花了很多时间将标题标签放入我的下拉列表中,如下所示:
public static HtmlString SelectFor<TModel, TProperty, TListItem>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<TListItem> enumeratedItems,
string idPropertyName,
string displayPropertyName,
string titlePropertyName,
object htmlAttributes) where TModel : class
{
//initialize values
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var propertyName = metaData.PropertyName;
var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();
var enumeratedType = typeof(TListItem);
//build the select tag
var returnText = string.Format("<select id=\"{0}\" name=\"{0}\"", HttpUtility.HtmlEncode(propertyName));
if (htmlAttributes != null)
{
foreach (var kvp in htmlAttributes.GetType().GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)))
{
returnText += string.Format(" {0}=\"{1}\"", …Run Code Online (Sandbox Code Playgroud) 我试图用来GetCustomAttributes()获取属性上定义的属性.问题是该属性是一个被覆盖的属性,我无法弄清楚如何从表达式中提取被覆盖的属性.我只能弄清楚如何获得基类.
这是一些代码
public class MyAttribute : Attribute
{
//...
}
public abstract class Text
{
public abstract string Content {get; set;}
}
public class Abstract : Text
{
[MyAttribute("Some Info")]
public override string Content {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
现在我试图MyAttribute摆脱抽象类.但我需要通过一个Expression.这就是我一直在使用的:
Expression<Func<Abstract, string>> expression = c => c.Content;
Expression exp = expression.Body;
MemberInfo memberType = (exp as MemberExpression).Member;
var attrs = Attribute.GetCustomAttributes(memberType, true);
Run Code Online (Sandbox Code Playgroud)
不幸的是atts最终为空.问题是menberType最终是为了Text.Content而不是Abstract.Content班级.因此,当我获得属性时,它什么都不返回.
我正在使用下面的方法来查询EF
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想创建动态Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>表达式来订购我的数据.
我只知道字段名称为字符串和顺序类型(升序,降序)为字符串(asc,desc)
我想使用Linq Expression树创建一个表达式来模拟这个:
List<int> ids = new List<int>();
// Fill ids with data
db.Where(a => ids.Contains(a.Id));
Run Code Online (Sandbox Code Playgroud)
这是我得到的地方,但我仍然遗漏了一些东西:
MemberExpression me = Expression.Property(pe, typeof(T).GetProperty(property));
Expression callContains = Expression.Call(typeof(System.Linq.Enumerable), "Contains", new Type[] { me.Type }, me);
Run Code Online (Sandbox Code Playgroud)
我怎样才能做我想做的事呢?
我对System.Linq.Expressions.LabelExpression和及其辅助类和方法有一些疑问。
1)LabelExpression该类的文档如下:
表示标签,可以将其放在任何Expression上下文中。如果跳转到,它将获得由所提供的值GotoExpression。否则,它将接收中的值DefaultValue。如果Type等于System.Void,则不提供任何值。
将值返回到标签目标是什么意思?换句话说,标签目标接收值意味着什么?我一生中从未做到过-跳到标签目标时将值传递给标签目标?
2)虽然到达标签目标完全合理,但返回并继续并打破标签目标意味着什么?
我想指定一个可以接受方法的参数,而不必指定泛型参数来生成给定方法的MethodInfo.
例如,我想写这样的代码:
interface IService
{
object AMethod(int p1, int p2);
}
IThingy<IService>() thingy;
thingy.Add(svc => svc.AMethod);
Run Code Online (Sandbox Code Playgroud)
我能提供的最接近的选择是:
interface IThingy<TService>
{
void Add1<T0, T1, TResult>(Expression<Func<TService, Func<T0, T1, TResult>>> expression);
void Add2(Expression<Func<TService, Func<int, int, object>>> expression);
void Add3(Expression<Action<TService>> expression);
}
thingy.Add1<int, int, object>(svc => svc.AMethod);
thingy.Add2(svc => svc.AMethod);
thingy.Add3(svc => svc.AMethod(0, 0));
Run Code Online (Sandbox Code Playgroud)
Add1意味着很多Func重载,我很好,但是如果不指定泛型参数就无法调用.
Add2不需要通用参数,但暗示每个参数签名都有特定的重载.
Add3需要调用该方法,包括伪参数.
仅供参考,我将处理表达式以获取给定方法的MethodInfo,如下所示:
MemberInfo GetMemberFromExpression<T>(Expression<ActionT>> expression)
{
return ((MethodCallExpression)expression.Body).Method
}
GetMemberFromExpression(svc => svc.AMethod(0, 0));
Run Code Online (Sandbox Code Playgroud) 我正在做一个Func - > Expression - > Func转换.如果我从方法(下面的第一个示例)创建Func <>(),它可以正常工作,但是如果我使用表达式树(第二个示例)创建函数,则在访问func2.Method.DeclaringType.FullName时它会因NullReferenceException而失败.这是因为DeclaringType为null.(NJection使用反射,所以我认为这就是它需要DeclaringType的原因.)
如何为通过编译表达式树创建的Func <>填写DeclaringType类型?(也许它不可能?)DeclaringType在第一个例子中设置.
使用方法中的Func <> ...(效果很好)
// Build a Func<>
Func<int, int> add = Add;
// Convert it to an Expression using NJection Library
Expression<Func<int, int>> expr = ToExpr<Func<int, int>>(add);
// Convert it back to a Func<>
Func < int, int> func = expr.Compile();
// Run the Func<>
int result = func(100);
Run Code Online (Sandbox Code Playgroud)
使用表达式树(不起作用)......
// Build a Func<> using an Expression Tree
ParameterExpression numParam = Expression.Parameter(typeof(int)); …Run Code Online (Sandbox Code Playgroud)