As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm looking for a formula interpreter that I can use in a C# application. It needs to be able to interpret a string like this:
max(1+2, 4) * x
I found Writing a fast formula interpreter (codeproject.com) which almost does what I need but it doesn't allow for functions with multiple parameters. I could probably add that functionality to it but I was just wondering if something like this already exists.
Thanks
A couple I've used in the past with no problems:
NCalc
Fast Lightweight Expression Evaluator
You can actually build a very effective interpreter by parsing and replacing certain functional keywords such as max with Math.Max and then dynamically building and executing the formula as a C# class and method. So actually you would be parsing and wrapping the formula and allowing the C# compiler to interpret and execute it.
So, taking your sample formula of max(1+2, 4) * x would turn into:
public class MyFormula
{
public double calc(double x)
{
return Math.Max(1+2, 4) * x;
}
}
Which you would compile on the fly and then execute per the linked article. You still have to parse for and pass the x value of course.
A long time ago in one project i had to create some booking with formulas, and i used VsaEngine. To use this engine you need to add reference to Microsoft.JScript. Here is example:
Code for usage is very simple, just replace formula parameters like:
string formula = "x+y";
formula= formula.Replace("x","100").Replace("y","200");
string result = CalculateFormula(formula);
And here is core method, CalculateFormula:
public string CalculateFormula(string evaluationString)
{
VsaEngine en = VsaEngine.CreateEngine();
Object result = Eval.JScriptEvaluate(evaluationString, en);
return result.ToString();
}
With this you can create your custom formula interpreter engine.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm a bit OCD about my code and wondered how other people structure the following sample control flow. I haven't found anything that passes my "pretty" code test.
var records = repo.GetRecords(batch:10);
while(records.Any())
{
var processed = ProcessRecords(records);
repo.DeleteRecords(processed);
records = repo.GetRecords(batch:10);
}
Thanks
Similar to #John Kugleman's above, but using while rather than for.
while (true)
{
var records = repo.GetRecords(batch:10);
if (!records.Any()) break;
var processed = ProcessRecords(records);
repo.DeleteRecords(processed);
}
You can also find questions like this:
Split List into Sublists with LINQ
That ask how to "chunkify" a sequence of items. That technique might or might not apply to your situation.
Assuming a Chunk extension method (similar to #TickleMeElmo's answer or Split from #JaredPar's answer), your code might look like this:
foreach (var chunk in repo.GetRecords().Chunk(10))
{
var processed = ProcessRecords(chunk);
repo.DeleteRecords(processed);
}
This idiom might not work that well if you already have some sort of "chunkification" built into to your repository.
while (true)
{
var records = repo.GetRecords(batch:10);
if (!records.Any())
break;
var processed = ProcessRecords(records);
repo.DeleteRecords(processed);
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
In c#, how can I find a specefic character in a string. this "2222+2222" is my string and I want to find the character "+" in it? I want a function that returns a bool if it finds it.
string.Contains("+") returns a bool.
yourString.IndexOf("+") will return 0 or a positive number if the character is found
Since you prefer something that returns bool, you can use Contains instead but notice that Contains does not provide an overload to perform a case-insensitive search. In scenarios where this is important (finding a string without caring for case), it's best to use IndexOf(stringToSearch,StringComparison.InvariantCultureIgnoreCase) to determine whether the string is found or not.
String s = "2222+2222";
if (s.Contains("+")) {
// dosomething...
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am trying to write a service in which every user will be assigned a unique name, when he first uses the service. I wish to generate this name, rather than getting the user to set it up. Also, I want the name to be somewhat readable and memorable rather than sound like a GUID or a timestamp. Essentially I want this to be something like the Xbox gamertag.
I know that there will never be more than a 1000 users so maintaining the uniqueness would not be a problem (another reason why I can afford to avoid GUIDs)
I am thinking of taking some adjectives, nouns etc. from the dictionary and generating random but unique combinations of those.
Any suggestions?
You could use a corpus of English language n-grams (say of three letter sequences) and use them to generate words that look like English, but are actually completely gibberish. This kind of data is essentially random, but has a softness for the nature of human language and memory.
This is similar to what I'm talking about, except it combines entire words into sentences probabilistically. I was thinking more of doing it by composing letter sequences into imaginary words.
EDIT actually this page discusses what I'm talking about.
This is just a code example to fully approach your problem. In case it doesn't solve it, please try to be more specific in your question. Pass to the following method an instance of the System.Random class and a list of words (your dictionary).
static string GetGuid(Random random, IList<string> words)
{
const int minGuidSize = 10;
const int maxGuidSize = 15;
var builder = new StringBuilder();
while (builder.Length < minGuidSize)
builder.Append(words[random.Next(words.Count)]);
return builder.ToString(0, Math.Min(builder.Length, maxGuidSize));
}
You can use this list of 10 000 random name:
http://www.opensourcecf.com/1/2009/05/10000-Random-Names-Database.cfm
or use this website to generate a random list of firstname:
http://www.fakenamegenerator.com/order.php
Safe way. maintain the list of remaining non used names.
Easy way (also very scalable) but unsafe. Rely on the unlikelyhood that 2 users randomly get the same id.
I would try to get 3 or 4 lists of about a thousand modalities and then randomly picking one value in each list. That would make about 10E12 possibilities which is enough to avoid collision for 1000 users.
JohnLampMartin2212
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm new to C#. Can anybody explain the following lines:
string value = "";
string tempValue = "=Fields!{0}.Value";
value = RemoveSpace(ReportDataTable.Columns[i].ColumnName);
value = String.Format(tempValue, value);
You need to read about string.Format which replaces each format item in a specified string with the text equivalent of a corresponding object's value.
RemoveSpace would be some method like Trim() to remove the space around the string.
you are formatting the value according to tempValue format, where {0} is place holder
for more info on string format see this
I assume that you want this line to be explained:
value = String.Format(tempValue, value);
String.Format creates strings from a pattern and values. It is a static method in the C# language. It receives a format string that specifies where the following arguments should inserted. The format string uses substitution markers.
So string.Format replaces the "{0}" in this string "=Fields!{0}.Value" with your value.
Side-note: you can (should) always consult MSDN first. Just type the method into google and the first link is probably the documentation.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
I came across a C# language feature today courtesy of ReSharper, the ?? operator. This helped make the code even more concise than my initial attempt. See below for iteration in improving lines/length/readability of code.
A first attempt could be something like..
if (usersEmail == null)
userName = firstName;
else
userName = usersEmail;
Refactored to..
userName = usersEmail == null ? firstName : usersEmail;
Initially I thought the above would be the most efficient/concise version, but there is a third step...
userName = usersEmail ?? firstName;
Id like to know if you have any similar examples where C# language features help with reducing lines of code and improving readability?
the using block, LINQ, anonymous delegates, the list would just go on..
C# has a very nice habit of introducing features in every major release that cut down the amount of code that you have to write.
The var keyword for implicit static typing and automatic properties are two good examples.
This thread has a lot of gems: Hidden Features of C#? (including the one you mentioned)
Using using keyword
Extension methods.
LINQ queries allowing you to express the query criteria better than a foreach loop