c# - Using Linq to select property using an expression -
c# - Using Linq to select property using an expression -
i have object this:
public class sheet { public decimal? value1 { get; set; } public decimal? value2 { get; set; } } i have linq query builds list of tuple<int, sheet>. int percentage value stored in our database. wrapper class, simplicity using tuple.
then have extension method
public static decimal calculatevalue(this list<tuple<int, sheet>> sheets, expression<func<tuple<int, sheet>, decimal?>> field) { //return sum of int / 100 * field } what want phone call (list built objects using linq)
list<tuple<int, sheet>> sheets = new list<tuple<int, sheet>>(); var value1 = sheets.calculatevalue(x => x.value1); var value2 = sheets.calculatevalue(x => x.value2); i not want utilize reflection. not want "magic" strings properties value1 or value2. there way extension method grab property using look , multiply percentage, , sum result across collection?
according api trying build, should pass property selector sheet object, not tuple<int, sheet>. can utilize simple func delegate instead of expression, because working in-memory objects.
it's not clear how going handle null values - makes no sense multiply null, utilize 0 instead of null (such values not impact sum):
public static decimal calculatevalue( list<tuple<int, sheet>> sheets, func<sheet, decimal?> field) { homecoming sheets.sum(t => t.item1 * field(t.item2).getvalueordefault() / 100); } keep in mind - when apply partition operator on 2 integers, integer division used. if item1 value less 100, partition produce 0 result. that's why set multiplication operator first.
c# linq
Comments
Post a Comment