1.Expression<Func<T,TResult>>是表达式

//使用LambdaExpression构建表达式树
Expression<Func<int, int, int, int>> expr = (x, y, z) => (x + y) / z;
Console.WriteLine(expr.Compile()(, , ));

https://msdn.microsoft.com/zh-cn/library/system.linq.expressions.expression(v=vs.100).aspx

https://msdn.microsoft.com/zh-cn/library/bb335710(v=vs.100).aspx

2.Func<T, TResult> 委托

封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
public delegate TResult Func<in T, out TResult>(T arg)
类型参数
in T
此委托封装的方法的参数类型。
该类型参数是逆变的。即可以使用指定的类型或派生程度更低的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
out TResult
此委托封装的方法的返回值类型。
该类型参数是协变的。即可以使用指定的类型或派生程度更高的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
参数
arg
类型:T
此委托封装的方法的参数。
返回值
类型:TResult
此委托封装的方法的返回值。

  string mid = ",middle part,";
///匿名写法
Func<string, string> anonDel = delegate(string param)
{
param += mid;
param += " And this was added to the string.";
return param;
};
///λ表达式写法
Func<string, string> lambda = param =>
{
param += mid;
param += " And this was added to the string.";
return param;
};
///λ表达式写法(整形)
Func<int, int> lambdaint = paramint =>
{
paramint = ;
return paramint;
};
///λ表达式带有两个参数的写法
Func<int, int, int> twoParams = (x, y) =>
{
return x*y;
};
MessageBox.Show("匿名方法:"+anonDel("Start of string"));
MessageBox.Show("λ表达式写法:" + lambda("Lambda expression"));
MessageBox.Show("λ表达式写法(整形):" + lambdaint().ToString());
MessageBox.Show("λ表达式带有两个参数:" + twoParams(, ).ToString());

来自:

http://blog.csdn.net/shuyizhi/article/details/6598013

3.使用Expression进行查询拼接

    public static class DynamicLinqExpressions
{ public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
} public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
} }

使用方法

       public static IEnumerable<T> FilterBy<T>(this IEnumerable<T> collection, IEnumerable<KeyValuePair<string, string>> query)
{
var filtersCount = int.Parse(query.SingleOrDefault(k => k.Key.Contains("filterscount")).Value); Expression<Func<T, bool>> finalquery = null; for (var i = ; i < filtersCount; i += )
{
var filterValue = query.SingleOrDefault(k => k.Key.Contains("filtervalue" + i)).Value;
var filterCondition = query.SingleOrDefault(k => k.Key.Contains("filtercondition" + i)).Value;
var filterDataField = query.SingleOrDefault(k => k.Key.Contains("filterdatafield" + i)).Value;
var filterOperator = query.SingleOrDefault(k => k.Key.Contains("filteroperator" + i)).Value; Expression<Func<T, bool>> current = n => GetQueryCondition(n, filterCondition, filterDataField, filterValue); if (finalquery == null)
{
finalquery = current;
}
else if (filterOperator == "")
{
finalquery = finalquery.Or(current);
}
else
{
finalquery = finalquery.And(current);
}
}; if (finalquery != null)
collection = collection.AsQueryable().Where(finalquery); return collection;
}

要使用AsQueryable,必须引入 LinqKit.EntityFramework;如果不使用AsQueryable将会报错。

4.关于SelectListItem的扩展

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.UI; namespace Web.Helper
{
public static class SelectListItemExtensions
{
/// <summary>
/// Data.ToSelectListItems(s=>s.Id,s=>s.Name);
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="baseEntities"></param>
/// <param name="valueExpression"></param>
/// <param name="textExpression"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> baseEntities, Expression<Func<T, string>> valueExpression, Expression<Func<T, string>> textExpression, object defaultValue = null)
{
dynamic valueNameObject = valueExpression.Body.GetType().GetProperty("Member").GetValue(valueExpression.Body, null);
dynamic textNameobject = textExpression.Body.GetType().GetProperty("Member").GetValue(textExpression.Body, null); var valueName = (string)valueNameObject.Name;
var textName = (string)textNameobject.Name; return ToSelectListItems(baseEntities, valueName, textName, null);
}
/// <summary>
/// Data.ToSelectListItems("Id", "Name")
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="baseEntities"></param>
/// <param name="valueName"></param>
/// <param name="textName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> baseEntities, string valueName, string textName, object defaultValue = null)
{
if (string.IsNullOrWhiteSpace(valueName) || string.IsNullOrWhiteSpace(textName))
{
return new List<SelectListItem>();
}
var selectListItem = new List<SelectListItem>();
if (defaultValue != null)
{
foreach (var baseEntity in baseEntities)
{
var itemValue = GetPropertyValue(baseEntity, valueName);
selectListItem.Add(new SelectListItem()
{
Value = itemValue.ToString(),
Text = GetPropertyValue(baseEntity, textName).ToString(),
Selected = itemValue == defaultValue
});
}
}
else
{
foreach (var baseEntity in baseEntities)
{
selectListItem.Add(new SelectListItem()
{
Value = GetPropertyValue(baseEntity, valueName).ToString(),
Text = GetPropertyValue(baseEntity, textName).ToString(),
});
}
} return selectListItem;
} public static object GetPropertyValue(object obj, string propertyName)
{
//反射去获得对象的某个属性值
//Type t = obj.GetType();
//PropertyInfo info = t.GetProperty(propertyName);
//return info.GetValue(obj, null); //设置为SetValue return DataBinder.GetPropertyValue(obj, propertyName);
//return DataBinder.Eval(obj, propertyName);
} }
}

原文:http://blog.csdn.net/nabila/article/details/8137169

Expression<Func<T,TResult>>和Func<T,TResult>的更多相关文章

  1. Expression<Func<T,TResult>>和Func<T,TResult> 与AOP与WCF

    1>>Expression<Func<T,TResult>>和Func<T,TResult>http://www.cnblogs.com/xcsn/p/ ...

  2. Expression<Func<TObject, bool>>与Func<TObject, bool>的区别

    Func<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后 ...

  3. lambda表达式Expression<Func<Person, bool>> 、Func<Person, bool>区别

    前言: 自己通过lambda表达式的封装,将对应的表达式转成字符串的过程中,对lambda表达式有了新的认识 原因: 很多开发者对lambda表达式Expression<Func<Pers ...

  4. Expression<Func<T, bool>>与Func<T, bool>的区别

    转自:http://www.cnblogs.com/wow-xc/articles/4952233.html Func<TObject, bool>是委托(delegate) Expres ...

  5. EF Core 封装方法Expression<Func<TObject, bool>>与Func<TObject, bool>区别

    unc<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后就 ...

  6. expression<Func<object,Bool>> 及 Func<oject,bool>用法

    using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using ...

  7. 从var func=function 和 function func()区别谈Javascript的预解析机制

    var func=function 和 function func()在意义上没有任何不同,但其解释优先级不同:后者会先于同一语句级的其他语句. 即: { var k = xx(); function ...

  8. onclick="func()"和 onclick = "return func()"区别

    onclick="func()" 表示只会执行 func , 但是不会传回 func 中之回传值onclick = "return func()" 则是 执行 ...

  9. 【转】int const A::func()和int A::func() const

    int const A::func() { return 0; }int A::func() const { return 0; } 上面的代码是合法的,其中A::func成员函数[只能在成员函数后面 ...

随机推荐

  1. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q32-Q34)

    Question 32You create a custom Web Part.You need to ensure that a custom property is visible in Edit ...

  2. android Java BASE64编码和解码一:基础

    今天在做Android项目的时候遇到一个问题,需求是向服务器上传一张图片,要求把图片转化成图片流放在 json字符串里传输. 类似这样的: {"name":"jike&q ...

  3. Linux useful command

    查看linux系统里面的各个目录.文件夹的大小和使用情况, 先切换到需要查看的目录,如果需要查看所有linux目录的使用情况就直接切换到系统跟目录,然后执行: du -h --max-depth=1 ...

  4. Android实战--短信发送器

    首先设计界面 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:t ...

  5. scanf 用法及陷阱(转)

    函数名: scanf 功 能: 执行格式化输入 用 法: int scanf(char *format[,argument,...]); scanf()函数是通用终端格式化输入函数,它从标准输入设备( ...

  6. Linux学习书目

    Linux基础 1.<Linux与Unix Shell 编程指南> C语言基础 1.<C Primer Plus,5th Edition>[美]Stephen Prata著 2 ...

  7. SAM4E单片机之旅——23、在AS6(GCC)中使用FPU

    浮点单元(Floating Point Unit,FPU),是用于处理浮点数运算的单元. 为使用FPU,除了需要启用FPU外,还需要对编译器进行设置,以使其针对浮点运算生成特殊的指令.虽然在Atmel ...

  8. JavaScript Patterns 3.2 Custom Constructor Functions

    When you invoke the constructor function with new, the following happens inside the function: • An e ...

  9. 烂泥:centos安装LVM方式

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 最近开始打算学习有关LVM逻辑卷的知识,由于以前没有接触过,看了很多有关这方面的视频.但是一直不深入.今天就先不管了,先把centos系统安装在LVM上 ...

  10. 07_旅行商问题(TSP问题,货郎担问题,经典NPC难题)

    问题来源:刘汝佳<算法竞赛入门经典--训练指南> P61 问题9: 问题描述:有n(n<=15)个城市,两两之间均有道路直接相连,给出每两个城市i和j之间的道路长度L[i][j],求 ...