-9

Is there a way in c# where I can get the result of the formula inside the string with multiple values and with Add, Subtract, Max, Min, Average, Mean, Median operators where Operands in any sub-expression can be more than 2?

Something like

var result = Eval("Max(1,2,3, Avg(4,5,6,7), 9+10+9.9, 11/12)")

or any other way (without splitting the string or evaluating each operation separately)?

I tried to search but did not get any complete solution. I found that RegEx, DataTable.Computer or Math library do not support operations with more than two values.

Imran Rizvi
  • 7,331
  • 11
  • 57
  • 101
  • alright, maybe I will create a library for it and post to help others; although I am surprised that they did not create such basic library :) – Imran Rizvi Dec 08 '20 at 07:40
  • 1
    There a multiple solutions but not built-in. Google should help. The duplicates do not support a rich set of functions, though.. – TaW Dec 08 '20 at 08:29
  • @Taw, I wouldn't call [codedom](https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/using-the-codedom) as "not build-in". – Sinatr Dec 08 '20 at 08:30
  • I think I asked the question the wrong way, forget to mention that my expression is in a string, secondly I was looking to evaluate result without writing custom code of formulas, something like regex – Imran Rizvi Dec 08 '20 at 08:31
  • @Sinatr: Well, it is somewherre in-between, imo, but isn't it really more of a tool to build stuff with and not an out-of-the-box mathematical expression interpreter? – TaW Dec 08 '20 at 08:34
  • 1
    @Taw, yeah, to use codedom you need to write [few lines](https://stackoverflow.com/a/12431508/1997232) of code first. After that you have a solid script engine available to any of your software by just copy/pasting said code. – Sinatr Dec 08 '20 at 08:36
  • @Sinatr: Very useful link, thanks for that. Now one 'only' has to transform the math to valid c# code.. - But then I think it would be much more flexible than the DB hacks. – TaW Dec 08 '20 at 08:47
  • link to alternate [solution](https://stackoverflow.com/questions/33958586/is-there-any-mathparser-that-parse-a-mathematical-string-expression-containing-a?rq=1) – TaW Dec 08 '20 at 08:57
  • the alternate solution does not provide solution with Max, min type of operators – Imran Rizvi Dec 11 '20 at 06:27

1 Answers1

0

It's not clear exactly what you're asking about, but if you're looking for versions of Max and Avg that support multiple input values, you can use LINQ:

using System.Linq;

var result = new[] { 1, 2, 3, new[] { 4, 5, 6, 7 }.Average(), 9 + 10, 11/12 }.Max();

The result is 19 because 9 + 10 is the greatest of those elements.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736