# 拉姆达表达式的一些常用知识

### 1、Distinct()方法的使用。

   public class MyEqualityComparer<T,V> : IEqualityComparer<T>
{
private Func<T, V> keyFunc;

private IEqualityComparer<V> comparer;

public MyEqualityComparer(Func<T, V> keyFunc, IEqualityComparer<V> comparer)
{
this.keyFunc = keyFunc;
this.comparer = comparer;
}

public MyEqualityComparer(Func<T, V> keyFunc)
: this(keyFunc, EqualityComparer<V>.Default)
{
}

public bool Equals(T x, T y)
{
return comparer.Equals(keyFunc(x), keyFunc(y));
}

public int GetHashCode(T obj)
{
return comparer.GetHashCode(keyFunc(obj));
}
}

拓展方法：

 public static class ExtensionsMethod
{
/// <summary>
/// 拓展distinct
/// </summary>
/// <typeparam name="T">源类型</typeparam>
/// <typeparam name="V">委托返回类型（根据V类型，排除重复项）</typeparam>
/// <param name="source">拓展源</param>
/// <param name="func">委托（执行操作）</param>
/// <returns></returns>
public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> func)
{
return source.Distinct(new MyEqualityComparer<T, V>(func));
}
}

           #region List Distinct 去重

var list=new List<Student>()
{
new Student(){Age = "18",Name = "zhangsan"},
new Student(){Age = "18",Name = "lisi"},
new Student(){Age = "19",Name = "zhangsan"},
};

var listDistinct = list.Distinct();

var listMyDistinct = list.Distinct(c => new {c.Name}).ToList();

#endregion


### 2、System.Linq.Expressions.Expression的使用。

 System.Linq.Expressions.Expression<Func<string, bool>> pre = s => false;
System.Linq.Expressions.Expression<Func<string, bool>> expression = e => false;

expression.And(c => c != "");

List<string> preList = new List<string>()
{
"huage",
"zhangsan",
"lisi",
"wangwu",
"zhaolu",
"tianqi"
};

preList.Remove(null);
preList.Remove("huage");

if (preList.Contains("zhangsan"))
{
pre = pre.Or(c => c.Contains("zhangsan"));
}

if (preList.Contains("wangwu"))
{
pre = pre.Or(c => c.Contains("wangwu"));
}

var listStra = preList.Where(pre.Compile()).ToList();


常用的拓展方法

 public static class ExtensionsMethod
{
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>> expression1,
Expression<Func<T, bool>> expression2)
{
var invokedExpression = Expression.Invoke(expression2, expression1.Parameters
.Cast<Expression>());

return Expression.Lambda<Func<T, bool>>(Expression.Or(expression1.Body, invokedExpression),
expression1.Parameters);
}

public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1,
Expression<Func<T, bool>> expression2)
{
var invokedExpression = Expression.Invoke(expression2, expression1.Parameters
.Cast<Expression>());

return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body,
invokedExpression), expression1.Parameters);
}

}


posted @ 2020-05-09 11:30  华临天下  阅读(466)  评论(0编辑  收藏  举报