How do I order a bool by null first, then true, then false
return View("Index", db.HolidayRequestForms.ToList().OrderByDescending(e => e.Approved).ThenBy(e => e.RequestID))
I am using a using a custom display template for the bool, I don't know if that matters
You could use a custom comparer
public class ApprovedComparer : IComparer<bool?>
{
public int Compare(bool? x, bool? y)
{
var a = 0;
var b = 0;
if (x.HasValue)
a = x.Value ? 1 : 2;
if (y.HasValue)
b = y.Value ? 1 : 2;
return a - b;
}
}
Usage:
return View("Index", db.HolidayRequestForms.ToList()
.OrderBy(e => e.Approved, new ApprovedComparer())
.ThenBy(e => e.RequestID))
Can be tested in LinqPad (or a normal console app)
public class Thing
{
public string Name { get; set; }
public bool? Approved { get; set; }
}
public class ApprovedComparer : IComparer<bool?>
{
public int Compare(bool? x, bool? y)
{
var a = 0;
var b = 0;
if (x.HasValue)
a = x.Value ? 1 : 2;
if (y.HasValue)
b = y.Value ? 1 : 2;
return a - b;
}
}
void Main()
{
var thing1 = new Thing { Approved = null, Name = "Thing 1" };
var thing2 = new Thing { Approved = true, Name = "Thing 2", };
var thing3 = new Thing { Approved = false, Name = "Thing 3" };
//note the 'incorrect' order
var listOfThings = new[] { thing3, thing2, thing1 };
listOfThings
.OrderBy(x => x.Approved, new ApprovedComparer())
.Select(x => x.Name) //just for outputting the names
.Dump(); //LinqPad specifc
}
Output
As of .net 4.5, you can use Comparer<T>.Create() to create a static comparer, which can be 'inline' - ie, no separate class required.
Personally, I find the separate class a bit cleaner to read. Just my opinion, however.
var comparer = Comparer<bool?>.Create((x, y) =>
{
var a = 0;
var b = 0;
if (x.HasValue)
a = x.Value ? 1 : 2;
if (y.HasValue)
b = y.Value ? 1 : 2;
return a - b;
});
listOfThings
.OrderBy(x => x.Approved, comparer)
.Select(x => x.Name) //just for outputting the names
.Dump(); //LinqPad specifc
You can use this:
myList.OrderBy(v => !v)
Related
I have following classes and enum:
public class StatusCount
{
public string Status { get; set; }
public int Count { get; set; }
}
public enum myEnum {
A,
B,
C
}
public async Task<List<StatusCount>> GetStatusCount()
{
var listOfEnums = System.Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToList();//A,B,C
var query1 =_dbcontext.Table1.Include().Where().Count();//10
var query2 =_dbcontext.Table2.Include().Where().Count();//5
var query2 =_dbcontext.Table3.Include().Where().Count();//15
return ???
}
Output I want from GetStatusCount method is like below and need to return list to controller. Not sure how to map/send query1 count value with status 'A' and so on.
[
{
status:A
count: 10
},
{
status:B
count: 5
},
{
status:C
count: 15
}
]
Probably you need here grouping by constant. It will allow to use Count and return IQueryable
public async Task<List<StatusCount>> GetStatusCount()
{
var query1 = _dbcontext.Table1.Where(...).GroupBy(x => 1).Select(x => new StatusCount{ Status = "A", Count = g.Count() });
var query2 = _dbcontext.Table2.Where(...).GroupBy(x => 1).Select(x => new StatusCount{ Status = "B", Count = g.Count() });
var query3 = _dbcontext.Table3.Where(...).GroupBy(x => 1).Select(x => new StatusCount{ Status = "C", Count = g.Count() });
return query1.Concat(query2).Concat(query3).ToListAsync();
}
Given:
class T
{
public string A { get; set; }
public string B { get; set; }
}
string s = "A|B";
Is there a way to split s on the | and return a T object "inline"? I know I can do something like:
s.Select(x => { string[] arr = s.Split(); return new T() { A = arr[0], B = arr[1] };
But I'm wondering if there is some obscure linq thing to do it "inline" without declaring the array and splitting inside of the select. Something more along the lines of:
s.Split().Select(x => new T() { A = x[0], B = x[1] });
Obviously that'll give you a compiler error, but you get the idea... is there a way to do it like that?
If you want to do it in one line, sure:
var s = "A|B";
var t = new T{ A = s.Split('|')[0], B = s.Split('|')[1] };
But obviously that uses Split twice and it looks bad.
This is probably a sign that you need a method:
private static T ParseT(string s) {
// do the conversion *properly* here
}
Then you can just call it:
ParseT("A|B")
Alternatively, add an explicit (recommended) or implicit conversion:
public static explicit operator T(string s) {
// do the conversion *properly* here
}
If you use query syntax then you could do something like this:
var strings=new string[] { "A|B","C|D"};
var query= from s in strings
let x=s.Split('|')
select new T{ A = x[0], B = x[1] };
Update
If "A|B" is the data source I don't recommend use Linq for that, you just could do:
var arr= str.Split('|');
var instance=new T{A = arr[0],B=arr[1]};
Or do the same in the constructor as #James recommended in his answer.
It's not really better than what you originally had, but this is one way (if s is a IEnumerable<string>:
s.Select(x=>x.Split('|')).Select(x=>new T{A=x[0],B=x[1]});
if s is a single string, then you would do:
new List<string>{s} // Now List<string> with 1 string in the list
.Select(x=>x.Split('|')) // now IEnumerable<string[]> with 1 string array in it
.Select(x=>new T{A=x[0],B=x[1]}) // now IEnumerable<T> with 1 T in it
.First(); // Now just T
Why fight actual language concepts:
void Main()
{
var strs = new List<string> { "A|B", "CCC|DD", "E|FFF"};
var Ts = strs.Select(s =>s.ToT() );
Ts.Dump();
}
static class Ext
{
static public T ToT(this string str)
{
return new T(str);
}
}
public class T
{
public string A { get; set; }
public string B { get; set; }
public T(string str)
{
var arr= str.Split('|');
A = arr[0];
B = arr[1];
}
}
NOTE I do not recommend doing it this way this was more of a fun way to do.
public static T CreateLinq(string s)
{
return s.Aggregate((a: new StringBuilder(), b: new StringBuilder(), c: false),
(acc, c) => (a: (!acc.c && c != '|' ? acc.a.Append(c) : acc.a),
b: (acc.c && c != '|' ? acc.b.Append(c) : acc.b),
c: acc.c || c == '|'),
acc => new T { A = acc.a.ToString(), B = acc.b.ToString() });
}
And the performance is not as bad as it seams on the first glance.
public class T
{
public string A { get; set; }
public string B { get; set; }
};
static void Main(string[] args)
{
var s1 = Enumerable.Range(0, 1000000).Aggregate(new StringBuilder(), (acc, i) => acc.Append("A")).ToString();
var s2 = Enumerable.Range(0, 1000000).Aggregate(new StringBuilder(), (acc, i) => acc.Append("B")).ToString();
var text =$"{s1}|{s2}";
for (int i = 0; i < 5; i++)
{
Stopwatch sw = new Stopwatch();
Console.WriteLine("Start");
sw.Start();
var t1 = CreateT(text);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
var t2 = CreateLinq(text);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Reset();
}
Console.ReadLine();
}
public static T CreateLinq(string s)
{
return s.Aggregate((a: new StringBuilder(), b: new StringBuilder(), c: false),
(acc, c) => (a: (!acc.c && c != '|' ? acc.a.Append(c) : acc.a),
b: (acc.c && c != '|' ? acc.b.Append(c) : acc.b),
c: acc.c || c == '|'),
acc => new T { A = acc.a.ToString(), B = acc.b.ToString() });
}
public static T CreateT(string s)
{
var split = s.Split('|');
return new T { A = split[0], B = split[1] };
}
I have read about the IEqualityComparer interface. Here is my code (which says more then a thousand words)
static void Main(string[] args)
{
var Send = new ObservableCollection<ProdRow>() {
new ProdRow() { Code = "8718607000065", Quantity = 1 },
new ProdRow() { Code = "8718607000911", Quantity = 10 }
};
var WouldSend = new ObservableCollection<ProdRow>() {
new ProdRow() { Code = "8718607000065", Quantity = 1 },
new ProdRow() { Code = "8718607000072", Quantity = 1 },
new ProdRow() { Code = "8718607000256", Quantity = 1 },
new ProdRow() { Code = "8718607000485", Quantity = 1 },
new ProdRow() { Code = "8718607000737", Quantity = 1 },
new ProdRow() { Code = "8718607000911", Quantity = 20 }
};
//var sendToMuch = Send.Except(WouldSend).ToList();
//var sendToLittle = WouldSend.Except(Send).ToList();
//if (sendToMuch.Any() || sendToLittle.Any())
// var notGood = true;
//else
// var okay = true;
var sendToMuch = Send.ToList();
var sendToLittle = WouldSend.ToList();
foreach (var s in Send) {
var w = WouldSend.FirstOrDefault(d => d.Code.Equals(s.Code));
if (w != null) {
if (w.Quantity == s.Quantity) {
sendToMuch.Remove(s);
sendToLittle.Remove(w);
continue;
}
if (w.Quantity > s.Quantity) {
sendToLittle.Single(l => l.Code == w.Code).Quantity = (w.Quantity - s.Quantity);
sendToMuch.Remove(s);
} else {
sendToMuch.Single(l => l.Code == w.Code).Quantity = (s.Quantity - w.Quantity);
sendToLittle.Remove(s);
}
} else {
sendToMuch.Add(s);
}
}
}
The commented lines where what I would hoped that would work... the stuff below with what I ended up with.
As reference, here is my ProdRow class:
class ProdRow : INotifyPropertyChanged, IEqualityComparer<ProdRow>
{
private string _code;
private int _quantity;
public string Code {
get { return _code; }
set {
_code = value;
OnPropertyChanged("Code");
}
}
public int Quantity {
get { return _quantity; }
set {
_quantity = value;
OnPropertyChanged("Quantity");
}
}
private void OnPropertyChanged(string v) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v));
}
public new bool Equals(object x, object y) {
if (((ProdRow)x).Code.Equals(((ProdRow)y).Code) && ((ProdRow)x).Quantity == ((ProdRow)y).Quantity)
return true;
else
return false;
}
public int GetHashCode(object obj) {
return obj.GetHashCode();
}
public bool Equals(ProdRow x, ProdRow y) {
if (x.Code.Equals(y.Code) && x.Quantity == y.Quantity)
return true;
else
return false;
}
public int GetHashCode(ProdRow obj) {
throw new NotImplementedException();
}
public event PropertyChangedEventHandler PropertyChanged;
}
I did not expected the commented part to work, because it cannot know to decrease the int of quantity etc. but I would like to know if there is a more efficient way to do this then the solution I used (below the commented lines). Perhaps flatten the collection like a string[]?
P.S. Sorry for the "PascalCase" of Send and WouldSend
IEqualityComparer<T> is not the right interface to implement for a class whose instances you wish to compare. IEqualityComparer<T> implementations are for creating objects that do comparisons from the outside of the objects being compared, which becomes important when you need to re-define what it means for two objects to be equal without access to the code of these objects, or when you need to use different semantic for equality depending on the context.
The right interface for strongly typed equality comparison is IEquatable<T>. However, in your case all you need is overriding Object's Equals(object) and GetHashCode():
public new bool Equals(object obj) {
if (obj == this) return true;
var other = obj as ProdRow;
if (other == null) return false;
return Code.Equals(other.Code) && Quantity == other.Quantity;
}
public int GetHashCode() {
return 31*Code.GetHashCode() + Quantity;
}
As far as computing quantities goes, you can do it with negative numbers and GroupBy:
var quantityByCode = WouldSend.Select(p => new {p.Code, p.Quantity})
.Concat(Send.Select(p => new {p.Code, Quantity = -p.Quantity}))
.GroupBy(p => p.Code)
.ToDictionary(g => g.Key, g => g.Sum(p => p.Quantity));
var tooLittle = quantityByCode
.Where(p => p.Value > 0)
.Select(p => new ProdRow {Code = p.Key, Quantity = p.Value})
.ToList();
var tooMuch = quantityByCode
.Where(p => p.Value < 0)
.Select(p => new ProdRow {Code = p.Key, Quantity = -p.Value})
.ToList();
This is my list
int specifiedvalue=6.5;
Name Value
A 6.5
A 6.0
B 6.5
B 6.0
C 7.75
D 7.0
I would like to remove from this list objects which have the same name and a different value than the specifiedvalue(6.5) and keep the rest.
The result should be like:
A 6.5
B 6.5
C 7.75
D 7.0
Thanks
First of all you wrote that, the type of the specifiedValue is int. But the vaue is floating point and you must change it as double.
I am supposing that, you have declared your class like that:
public class Lens
{
public string Name { get; set; }
public double Value { get; set; }
public Lens(string name, double value)
{
Name = name;
Value = value;
}
}
Here I am initializing the objects:
double specidifedValue = 6.5;
List<Lens> pairs = new List<Lens>();
pairs.Add(new Lens("A", 6.5));
pairs.Add(new Lens("A", 6.0));
pairs.Add(new Lens("B", 6.5));
pairs.Add(new Lens("B", 6.0));
pairs.Add(new Lens("C", 7.75));
pairs.Add(new Lens("D", 7.0));
And with that, firstly I am finding Names which are occured more than one time in the list. And then selecting those with the value 6.5.
var keysMoreThanOne = pairs.GroupBy(x => x.Name)
.Where(x => x.Count() > 1).Select(x => x.Key).ToList();
List<Lens> filteredPairs = pairs
.Where(x => (keysMoreThanOne.Contains(x.Name) && x.Value == specidifedValue)
|| !keysMoreThanOne.Contains(x.Name)).ToList();
The result is as you want.
Update:
var result = new List<Lens>();
var keysMoreThanOne = pairs.GroupBy(x => x.Name).Where(x => x.Count() > 1).Select(x => x.Key).ToList();
if (specidifedValue > 0)
{
result = pairs.Where(x => (keysMoreThanOne.Contains(x.Name) && x.Value == specidifedValue) ||
!keysMoreThanOne.Contains(x.Name)).ToList();
}
else
{
result = pairs.Where(x => (keysMoreThanOne.Contains(x.Name) &&
x.Value == pairs.Where(y=> y.Name==x.Name).OrderByDescending(y=> y.Value).First().Value)
|| !keysMoreThanOne.Contains(x.Name)).ToList();
}
internal class NameValue
{
public string Name { get; set; }
public double Value { get; set; }
}
var sourceList = new List<NameValue>
{
new NameValue {Name = "A", Value = 6.5},
new NameValue {Name = "A", Value = 6.0},
new NameValue {Name = "B", Value = 6.5},
new NameValue {Name = "B", Value = 6.0},
new NameValue {Name = "C", Value = 7.75},
new NameValue {Name = "D", Value = 7.0}
};
var result = sourceList.GroupBy(x => x.Name)
.Select(x => new
{
Name = x.Key,
Value = x.Max(y => y.Value)
});
Here what we want to do.
We have data from the database that we need to format to make a report, including some calculation (Sum, Averages, and field to field calculation (ex : x.a / x.b)).
One of the limitations is that if, in a sum for exemple, one of the data is null, -1 or -2 we have to stop the calculation and display '-'. Since we have many reports to produce, with the same logic and many calculation in each, we want to centralise this logic. For now, the code we produce allow us to check for field to field calculation (x.a / x.b for exemple), but can't allow us to check for group total (ex: x.b / SUM(x.a))
Test case
Rules
The calcul should not be done if one of the value used in the calcul is -1, -2 or null. In this case, return "-" if you find -1 or null, and "C" if you find -2
If you have multiple "bad values" in the calcul, you need to respect a priority defined like this: null -> -1 -> -2. This priority is independant of the level where the value is in the calcul
Tests
Simple calcul
object: new DataInfo { A = 10, B = 2, C = 4 }
calcul: x => x.A / x.B + x.C
result: 9
object: new DataInfo { A = 10, B = 2, C = -2 }
calcul: x => x.A / x.B + x.C
result: C (because you have a '-2' value in the calcul)
object: new DataInfo { A = 10, B = -2, C = null }
calcul: x => x.A / x.B + x.C
result: - (because you have a 'null' value in the calcul and it win on the -2 value)
Complex calcul
object: var list = new List();
list.Add(new DataInfo { A = 10, B = 2, C = 4 });
list.Add(new DataInfo { A = 6, B = 3, C = 2 });
calcul: list.Sum(x => x.A / x.B + list.Max(y => y.C))
result: 15
object: var list = new List();
list.Add(new DataInfo { A = 10, B = 2, C = 4 });
list.Add(new DataInfo { A = 6, B = 3, C = -2 });
calcul: list.Sum(x => x.A / x.B + list.Max(y => y.C))
result: C (because you have a '-2' value in the calcul)
What we have done so far
Here the code we have to handle simple calculs, based on this thread:
How to extract properties used in a Expression<Func<T, TResult>> query and test their value?
We have created a strongly type class that perform a calcul and return the result as a String. But if any part of the expression is equal to a special value, the calculator has to return a special character.
It works well for a simple case, like this one:
var data = new Rapport1Data() { UnitesDisponibles = 5, ... };
var q = new Calculator<Rapport1Data>()
.Calcul(data, y => y.UnitesDisponibles, "N0");
But I need to be able to perform something more complicated like:
IEnumerable<Rapport1Data> data = ...;
var q = new Calculator<IEnumerable<Rapport1Data>>()
.Calcul(data, x => x.Sum(y => y.UnitesDisponibles), "N0");
When we start encapsulating or data in IEnurmarable<> we get an error:
Object does not match target type
As we understand it, it's because the Sub-Expression y => y.UnitesDisponibles is being applied to the IEnumerable instead of the Rapport1Data.
How can we fix it to ensure that it will be fully recursive if we some day have complex expression like:
IEnumerable<IEnumerable<Rapport1Data>> data = ...;
var q = new Calculator<IEnumerable<IEnumerable<Rapport1Data>>>()
.Calcul(data,x => x.Sum(y => y.Sum(z => z.UnitesDisponibles)), "N0");
Classes we've built
public class Calculator<T>
{
public string Calcul(
T data,
Expression<Func<T, decimal?>> query,
string format)
{
var rulesCheckerResult = RulesChecker<T>.Check(data, query);
// l'ordre des vérifications est importante car il y a une gestion
// des priorités des codes à retourner!
if (rulesCheckerResult.HasManquante)
{
return TypeDonnee.Manquante.ReportValue;
}
if (rulesCheckerResult.HasDivisionParZero)
{
return TypeDonnee.DivisionParZero.ReportValue;
}
if (rulesCheckerResult.HasNonDiffusable)
{
return TypeDonnee.NonDiffusable.ReportValue;
}
if (rulesCheckerResult.HasConfidentielle)
{
return TypeDonnee.Confidentielle.ReportValue;
}
// if the query respect the rules, apply the query and return the
// value
var result = query.Compile().Invoke(data);
return result != null
? result.Value.ToString(format)
: TypeDonnee.Manquante.ReportValue;
}
}
and the Custom ExpressionVisitor
class RulesChecker<T> : ExpressionVisitor
{
private readonly T data;
private bool hasConfidentielle = false;
private bool hasNonDiffusable = false;
private bool hasDivisionParZero = false;
private bool hasManquante = false;
public RulesChecker(T data)
{
this.data = data;
}
public static RulesCheckerResult Check(T data, Expression expression)
{
var visitor = new RulesChecker<T>(data);
visitor.Visit(expression);
return new RulesCheckerResult(
visitor.hasConfidentielle,
visitor.hasNonDiffusable,
visitor.hasDivisionParZero,
visitor.hasManquante);
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (!this.hasDivisionParZero &&
node.NodeType == ExpressionType.Divide &&
node.Right.NodeType == ExpressionType.MemberAccess)
{
var rightMemeberExpression = (MemberExpression)node.Right;
var propertyInfo = (PropertyInfo)rightMemeberExpression.Member;
var value = Convert.ToInt32(propertyInfo.GetValue(this.data, null));
this.hasDivisionParZero = value == 0;
}
return base.VisitBinary(node);
}
protected override Expression VisitMember(MemberExpression node)
{
// Si l'un d'eux n'est pas à true, alors continuer de faire les tests
if (!this.hasConfidentielle ||
!this.hasNonDiffusable ||
!this.hasManquante)
{
var propertyInfo = (PropertyInfo)node.Member;
object value = propertyInfo.GetValue(this.data, null);
int? valueNumber = MTO.Framework.Common.Convert.To<int?>(value);
// Si la valeur est à true, il n'y a pas lieu de tester davantage
if (!this.hasManquante)
{
this.hasManquante =
valueNumber == TypeDonnee.Manquante.BdValue;
}
// Si la valeur est à true, il n'y a pas lieu de tester davantage
if (!this.hasConfidentielle)
{
this.hasConfidentielle =
valueNumber == TypeDonnee.Confidentielle.BdValue;
}
// Si la valeur est à true, il n'y a pas lieu de tester davantage
if (!this.hasNonDiffusable)
{
this.hasNonDiffusable =
valueNumber == TypeDonnee.NonDiffusable.BdValue;
}
}
return base.VisitMember(node);
}
}
[UPDATE]
Adding more detail on what we want to do
There are a few things that you need to change to get this to work:
Create a new ExpressionVisitor that will preprocess your expression to execute the aggregates.
Use the new ExpressionVisitor in the Calculator.Calcul method.
Modify the RulesChecker to include an override for the VisitConstant method. This new method needs to include the same logic that is in the VisitMember method.
Modify the RulesChecker VisitBinary method to check the divide by zero condition for ConstantExpressions.
Here is a rough example of what I think needs to be done.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace WindowsFormsApplication1 {
internal static class Program {
[STAThread]
private static void Main() {
var calculator = new Calculator();
//// DivideByZero - the result should be -1
var data1 = new DataInfo { A = 10, B = 0, C = 1 };
Expression<Func<DataInfo, decimal?>> expression1 = x => x.A / x.B + x.C;
var result1 = calculator.Calcul(data1, expression1, "N0");
//// Negative 1 - the result should be -
var data2 = new DataInfo { A = 10, B = 5, C = -1 };
Expression<Func<DataInfo, decimal?>> expression2 = x => x.A / x.B + x.C;
var result2 = calculator.Calcul(data2, expression2, "N0");
//// Negative 2 - the result should be C
var data3 = new DataInfo { A = 10, B = 5, C = -2 };
Expression<Func<DataInfo, decimal?>> expression3 = x => x.A / x.B + x.C;
var result3 = calculator.Calcul(data3, expression3, "N0");
//// the result should be 3
var data4 = new DataInfo { A = 10, B = 5, C = 1 };
Expression<Func<DataInfo, decimal?>> expression4 = x => x.A / x.B + x.C;
var result4 = calculator.Calcul(data4, expression4, "N0");
//// DivideByZero - the result should be -1
var data5 = new List<DataInfo> {
new DataInfo {A = 10, B = 0, C = 1},
new DataInfo {A = 10, B = 0, C = 1}
};
Expression<Func<IEnumerable<DataInfo>, decimal?>> expression5 = x => x.Sum(y => y.A) / x.Sum(y => y.B) + x.Sum(y => y.C);
var result5 = calculator.Calcul(data5, expression5, "N0");
//// the result should be 4
var data6 = new List<DataInfo> {
new DataInfo {A = 10, B = 5, C = 1},
new DataInfo {A = 10, B = 5, C = 1}
};
Expression<Func<IEnumerable<DataInfo>, decimal?>> expression6 = x => x.Sum(y => y.A) / x.Sum(y => y.B) + x.Sum(y => y.C);
var result6 = calculator.Calcul(data6, expression6, "N0");
//// the result should be -
var data7 = new List<DataInfo> {
new DataInfo {A = 10, B = 5, C = -1},
new DataInfo {A = 10, B = 5, C = 1}
};
Expression<Func<IEnumerable<DataInfo>, decimal?>> expression7 = x => x.Sum(y => y.A) / x.Sum(y => y.B) + x.Sum(y => y.C);
var result7 = calculator.Calcul(data7, expression7, "N0");
//// the result should be 14
var c1 = 1;
var c2 = 2;
var data8 = new DataInfo { A = 10, B = 1, C = 1 };
Expression<Func<DataInfo, decimal?>> expression8 = x => x.A / x.B + x.C + c1 + c2;
var result8 = calculator.Calcul(data8, expression8, "N0");
}
}
public class Calculator {
public string Calcul<T>(T data, LambdaExpression query, string format) {
string reportValue;
if (HasIssue(data, query, out reportValue)) {
return reportValue;
}
// executes the aggregates
query = (LambdaExpression)ExpressionPreProcessor.PreProcessor(data, query);
// checks the rules against the results of the aggregates
if (HasIssue(data, query, out reportValue)) {
return reportValue;
}
Delegate lambda = query.Compile();
decimal? result = (decimal?)lambda.DynamicInvoke(data);
return result != null
? result.Value.ToString(format)
: TypeDonnee.Manquante.ReportValue;
}
private bool HasIssue(object data, LambdaExpression query, out string reportValue) {
reportValue = null;
var rulesCheckerResult = RulesChecker.Check(data, query);
if (rulesCheckerResult.HasManquante) {
reportValue = TypeDonnee.Manquante.ReportValue;
}
if (rulesCheckerResult.HasDivisionParZero) {
reportValue = TypeDonnee.DivisionParZero.ReportValue;
}
if (rulesCheckerResult.HasNonDiffusable) {
reportValue = TypeDonnee.NonDiffusable.ReportValue;
}
if (rulesCheckerResult.HasConfidentielle) {
reportValue = TypeDonnee.Confidentielle.ReportValue;
}
return reportValue != null;
}
}
internal class ExpressionPreProcessor : ExpressionVisitor {
private readonly object _source;
public static Expression PreProcessor(object source, Expression expression) {
if (!IsValidSource(source)) {
return expression;
}
var visitor = new ExpressionPreProcessor(source);
return visitor.Visit(expression);
}
private static bool IsValidSource(object source) {
if (source == null) {
return false;
}
var type = source.GetType();
return type.IsGenericType && type.GetInterface("IEnumerable") != null;
}
public ExpressionPreProcessor(object source) {
this._source = source;
}
protected override Expression VisitMethodCall(MethodCallExpression node) {
if (node.Method.DeclaringType == typeof(Enumerable) && node.Arguments.Count == 2) {
switch (node.Method.Name) {
case "Count":
case "Min":
case "Max":
case "Sum":
case "Average":
var lambda = node.Arguments[1] as LambdaExpression;
var lambaDelegate = lambda.Compile();
var value = node.Method.Invoke(null, new object[] { this._source, lambaDelegate });
return Expression.Constant(value);
}
}
return base.VisitMethodCall(node);
}
}
internal class RulesChecker : ExpressionVisitor {
private readonly object data;
private bool hasConfidentielle = false;
private bool hasNonDiffusable = false;
private bool hasDivisionParZero = false;
private bool hasManquante = false;
public RulesChecker(object data) {
this.data = data;
}
public static RulesCheckerResult Check(object data, Expression expression) {
if (IsIEnumerable(data)) {
var result = new RulesCheckerResult(false, false, false, false);
IEnumerable dataItems = (IEnumerable)data;
foreach (object dataItem in dataItems) {
result = MergeResults(result, GetResults(dataItem, expression));
}
return result;
}
else {
return GetResults(data, expression);
}
}
private static RulesCheckerResult MergeResults(RulesCheckerResult results1, RulesCheckerResult results2) {
var hasConfidentielle = results1.HasConfidentielle || results2.HasConfidentielle;
var hasDivisionParZero = results1.HasDivisionParZero || results2.HasDivisionParZero;
var hasManquante = results1.HasManquante || results2.HasManquante;
var hasNonDiffusable = results1.HasNonDiffusable || results2.HasNonDiffusable;
return new RulesCheckerResult(hasConfidentielle, hasNonDiffusable, hasDivisionParZero, hasManquante);
}
private static RulesCheckerResult GetResults(object data, Expression expression) {
var visitor = new RulesChecker(data);
visitor.Visit(expression);
return new RulesCheckerResult(
visitor.hasConfidentielle,
visitor.hasNonDiffusable,
visitor.hasDivisionParZero,
visitor.hasManquante);
}
private static bool IsIEnumerable(object source) {
if (source == null) {
return false;
}
var type = source.GetType();
return type.IsGenericType && type.GetInterface("IEnumerable") != null;
}
protected override Expression VisitBinary(BinaryExpression node) {
if (!this.hasDivisionParZero && node.NodeType == ExpressionType.Divide) {
if (node.Right.NodeType == ExpressionType.MemberAccess) {
var rightMemeberExpression = (MemberExpression)node.Right;
var propertyInfo = (PropertyInfo)rightMemeberExpression.Member;
var value = Convert.ToInt32(propertyInfo.GetValue(this.data, null));
this.hasDivisionParZero = value == 0;
}
if (node.Right.NodeType == ExpressionType.Constant) {
var rightConstantExpression = (ConstantExpression)node.Right;
var value = Convert.ToInt32(rightConstantExpression.Value);
this.hasDivisionParZero = value == 0;
}
}
return base.VisitBinary(node);
}
protected override Expression VisitConstant(ConstantExpression node) {
this.CheckValue(this.ConvertToNullableInt(node.Value));
return base.VisitConstant(node);
}
protected override Expression VisitMember(MemberExpression node) {
if (!this.hasConfidentielle || !this.hasNonDiffusable || !this.hasManquante) {
var propertyInfo = node.Member as PropertyInfo;
if (propertyInfo != null) {
var value = propertyInfo.GetValue(this.data, null);
this.CheckValue(this.ConvertToNullableInt(value));
}
}
return base.VisitMember(node);
}
private void CheckValue(int? value) {
if (!this.hasManquante) {
this.hasManquante = value == TypeDonnee.Manquante.BdValue;
}
if (!this.hasConfidentielle) {
this.hasConfidentielle = value == TypeDonnee.Confidentielle.BdValue;
}
if (!this.hasNonDiffusable) {
this.hasNonDiffusable = value == TypeDonnee.NonDiffusable.BdValue;
}
}
private int? ConvertToNullableInt(object value) {
if (!value.GetType().IsPrimitive) {
return int.MinValue;
}
// MTO.Framework.Common.Convert.To<int?>(value);
return (int?)value;
}
}
class RulesCheckerResult {
public bool HasConfidentielle { get; private set; }
public bool HasNonDiffusable { get; private set; }
public bool HasDivisionParZero { get; private set; }
public bool HasManquante { get; private set; }
public RulesCheckerResult(bool hasConfidentielle, bool hasNonDiffusable, bool hasDivisionParZero, bool hasManquante) {
this.HasConfidentielle = hasConfidentielle;
this.HasNonDiffusable = hasNonDiffusable;
this.HasDivisionParZero = hasDivisionParZero;
this.HasManquante = hasManquante;
}
}
class TypeDonnee {
public static readonly TypeValues Manquante = new TypeValues(null, "-");
public static readonly TypeValues Confidentielle = new TypeValues(-1, "-");
public static readonly TypeValues NonDiffusable = new TypeValues(-2, "C");
public static readonly TypeValues DivisionParZero = new TypeValues(0, "-1");
}
class TypeValues {
public int? BdValue { get; set; }
public string ReportValue { get; set; }
public TypeValues(int? bdValue, string reportValue) {
this.BdValue = bdValue;
this.ReportValue = reportValue;
}
}
class DataInfo {
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
}
}
If I understand correctly you're looking for a 'recursive sum' function. Might I suggest something like this?
var q = new Calculator<Rapport1Data>()
.Calcul(data, y => RecursiveCalc(y), "N0");
double RecursiveCalc(object toCalc)
{
var asRapport = toCalc as Rapport1Data;
if (asRapport != null)
return asRapport.UnitesDisponibles;
var asEnumerable = toCalc as IEnumerable;
if (asEnumerable != null)
return asEnumerable.Sum(y => RecursiveCalc(y));
return 0; // handle a condition for unexpected types
}
*note: code not tested, might not even compile