c# – 如何使用动态LINQ进行求和

前端之家收集整理的这篇文章主要介绍了c# – 如何使用动态LINQ进行求和前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下与 dynamic linq library一起出色的工作:
  1. string where = "Price < 5";
  2. string orderby = "BookID ASC";
  3. IQueryable<T> MyDataQueryable = _DataRawBase.AsQueryable<T>();
  4. MyDataQueryable = MyDataQueryable.Where(where).OrderBy(orderby);

现在我想查询MyDataQueryable来做某些字段的SUM(也许是平均值).

我该怎么做?

就像是:

  1. double mysum = MyDataQueryable.Sum("Price");

会好的…

解决方法

由于所有内容都是字符串类型,您可能需要尝试:
  1. var myDataQueryable = _DataRawBase.AsQueryable<T>()
  2. .Sum("Price");

使用以下扩展方法

  1. public static object Sum(this IQueryable source,string member)
  2. {
  3. if (source == null) throw new ArgumentNullException(nameof(source));
  4. if (member == null) throw new ArgumentNullException(nameof(member));
  5.  
  6. // The most common variant of Queryable.Sum() expects a lambda.
  7. // Since we just have a string to a property,we need to create a
  8. // lambda from the string in order to pass it to the sum method.
  9.  
  10. // Lets create a ((TSource s) => s.Price ). First up,the parameter "s":
  11. ParameterExpression parameter = Expression.Parameter(source.ElementType,"s");
  12.  
  13. // Followed by accessing the Price property of "s" (s.Price):
  14. PropertyInfo property = source.ElementType.GetProperty(member);
  15. MemberExpression getter = Expression.MakeMemberAccess(parameter,property);
  16.  
  17. // And finally,we create a lambda from that. First specifying on what
  18. // to execute when the lambda is called,and finally the parameters of the lambda.
  19. Expression selector = Expression.Lambda(getter,parameter);
  20.  
  21. // There are a lot of Queryable.Sum() overloads with different
  22. // return types (double,int,decimal,double?,int?,etc...).
  23. // We're going to find one that matches the type of our property.
  24. MethodInfo sumMethod = typeof(Queryable).GetMethods().First(
  25. m => m.Name == "Sum"
  26. && m.ReturnType == property.PropertyType
  27. && m.IsGenericMethod);
  28.  
  29. // Now that we have the correct method,we need to know how to call the method.
  30. // Note that the Queryable.Sum<TSource>(source,selector) has a generic type,// which we haven't resolved yet. Good thing is that we can use copy the one from
  31. // our initial source expression.
  32. var genericSumMethod = sumMethod.MakeGenericMethod(new[] { source.ElementType });
  33.  
  34. // TSource,source and selector are now all resolved. We now know how to call
  35. // the sum-method. We're not going to call it here,we just express how we're going
  36. // call it.
  37. var callExpression = Expression.Call(
  38. null,genericSumMethod,new[] {source.Expression,Expression.Quote(selector)});
  39.  
  40. // Pass it down to the query provider. This can be a simple LinqToObject-datasource,// but also a more complex datasource (such as LinqTosql). Anyway,it knows what to
  41. // do.
  42. return source.Provider.Execute(callExpression);
  43. }

猜你在找的C#相关文章