I have query parameters such as /api/items?sizes=m,l,xxl, meaning they are separated by commas. I want to accept them as array of strings ([FromQuery] string[] sizes).
How do I do that? I know how to split the string, the issue is how do I accept string[] and let make sure it knows how to split the string?
string[] sizes = request.Sizes.Split(",", StringSplitOptions.RemoveEmptyEntries);
Such transformation is not supported even for MVC binders (it will require query string in one of the following formats: ?sizes[0]=3344&sizes[1]=2222 or ?sizes=24041&sizes=24117).
You can try using custom binding:
public class ArrayParser
{
public string[] Value { get; init; }
public static bool TryParse(string? value, out ArrayParser result)
{
result = new()
{
Value = value?.Split(',', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>()
};
return true;
}
}
And usage:
app.MapGet("/api/query-arr", (ArrayParser sizes) => sizes.Value);
Try using %2c in the URL to replace the commas.
what does out mean in a multidimensional param, if it's possible write an eg please, I'll really appreciate
public string GetTeamsInfo(out string[][] teams)
{
...
}
out means the parameter is an {out}put parameter
opposed to the default input parameter (note: an input parameter is not the same as a parameter using the in modifier, that is an input only parameter and imposes it own requirements)
this means it has no value at the beginning of the function and you need to assign one for it to be passed back to the calling code
see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
public string GetTeamsInfo(out string[][] teams)
{
teams = new string[3][4];
return "test";
}
string[][] teams;
//here teams is null
string text = GetTeamsInfo(out teams);
//here teams is a array of string[]
This is method to Convert String[] To String.
private string ConvertStringArrayToString(System.String[] array)
{
string result = string.Join("<br />", array);
return result.ToString();
}
This is unit test case method for the above method.
[TestMethod]
public void ConvertStringArrayToString_shouldReturnString()
{
string returnedString = null;
PrivateObject o = new PrivateObject(typeof(DemoClass));
System.String[] array = new System.String[]
{
"Index0","Index0","Index0","Index0"
};
returnedString = (string)Convert.ChangeType((o.Invoke("ConvertStringArrayToString", array)), typeof(string));
}
This results in missing method exception.
I found the error is in Passing parameter i.e. string[]
But when I replace method access specifier as public, the test case works without error!
Please help why method cannot be able to access when it is private and string[].
I believe the problem is that array is being passed directly as the argument for the object[] parameter, whereas you really want it to be wrapped so it's just the first argument in an array of arguments. So I'd write this:
string[] array = { "Index0", "Index0", "Index0", "Index0" };
object[] args = { array };
var result = o.Invoke("ConvertStringArrayToString", args);
string returnedString = (string) result;
(There's no need to declare returnedString earlier, and you don't need to use Convert.ChangeType - a cast should be fine.)
I call a few VBA methods from my C# project. This has caused me to repeat code in my project. So I created a C# method for the few that take the same amount of parameters but a few take different amounts. So I thought about a solution, all the parameters that I pass in are strings, so what if I pass in to my C# method a string array, then convert that string array in to individual strings in the VBA subprocedure call. This is what I have:
private static void RunVBAMethod(Excel.Application excelApp, string logFile, string vBAMethod, string [] args, out string errorType)
{
errorType = CSharpError;
var VbaCrashed = excelApp.Run(vBAMethod, ConvertStringArrayToString(args));
if (VbaCrashed != "False")
{
errorType = VBAError;
throw new Exception(VbaCrashed);
}
}
Here is my ConvertArrayToString method:
private static string ConvertStringArrayToString(string[] array)
{
// Concatenate all the elements into a StringBuilder.
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
builder.Append(',');
}
return builder.ToString();
}
Then I call it like this:
RunVBAMethod(excelApp, LogFile, "CleanMRP", new string[] { CurrentWorkbook.TimePeriod, CurrentWorkbook.Version, RemoveSpace(CurrentWorkbook.ReportType), CurrentWorkbook.MainMRPFilePath + CurrentWorkbook.FileName, HeaderRow.ToString(), CurrentWorkbook.DataPath }, out ExcelCrashed);
When I run it, it crashes on the excelApp.Run line saying Parameter not optional. Is, what I am trying to do even possible? Am I looking at the wrong way to do, if it is? or am I missing something so small?
I am trying to create a generic formatter/parser combination.
Example scenario:
I have a string for string.Format(), e.g. var format = "{0}-{1}"
I have an array of object (string) for the input, e.g. var arr = new[] { "asdf", "qwer" }
I am formatting the array using the format string, e.g. var res = string.Format(format, arr)
What I am trying to do is to revert back the formatted string back into the array of object (string). Something like (pseudo code):
var arr2 = string.Unformat(format, res)
// when: res = "asdf-qwer"
// arr2 should be equal to arr
Anyone have experience doing something like this? I'm thinking about using regular expressions (modify the original format string, and then pass it to Regex.Matches to get the array) and run it for each placeholder in the format string. Is this feasible or is there any other more efficient solution?
While the comments about lost information are valid, sometimes you just want to get the string values of of a string with known formatting.
One method is this blog post written by a friend of mine. He implemented an extension method called string[] ParseExact(), akin to DateTime.ParseExact(). Data is returned as an array of strings, but if you can live with that, it is terribly handy.
public static class StringExtensions
{
public static string[] ParseExact(
this string data,
string format)
{
return ParseExact(data, format, false);
}
public static string[] ParseExact(
this string data,
string format,
bool ignoreCase)
{
string[] values;
if (TryParseExact(data, format, out values, ignoreCase))
return values;
else
throw new ArgumentException("Format not compatible with value.");
}
public static bool TryExtract(
this string data,
string format,
out string[] values)
{
return TryParseExact(data, format, out values, false);
}
public static bool TryParseExact(
this string data,
string format,
out string[] values,
bool ignoreCase)
{
int tokenCount = 0;
format = Regex.Escape(format).Replace("\\{", "{");
for (tokenCount = 0; ; tokenCount++)
{
string token = string.Format("{{{0}}}", tokenCount);
if (!format.Contains(token)) break;
format = format.Replace(token,
string.Format("(?'group{0}'.*)", tokenCount));
}
RegexOptions options =
ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
Match match = new Regex(format, options).Match(data);
if (tokenCount != (match.Groups.Count - 1))
{
values = new string[] { };
return false;
}
else
{
values = new string[tokenCount];
for (int index = 0; index < tokenCount; index++)
values[index] =
match.Groups[string.Format("group{0}", index)].Value;
return true;
}
}
}
You can't unformat because information is lost. String.Format is a "destructive" algorithm, which means you can't (always) go back.
Create a new class inheriting from string, where you add a member that keeps track of the "{0}-{1}" and the { "asdf", "qwer" }, override ToString(), and modify a little your code.
If it becomes too tricky, just create the same class, but not inheriting from string and modify a little more your code.
IMO, that's the best way to do this.
It's simply not possible in the generic case. Some information will be "lost" (string boundaries) in the Format method. Assume:
String.Format("{0}-{1}", "hello-world", "stack-overflow");
How would you "Unformat" it?
Assuming "-" is not in the original strings, can you not just use Split?
var arr2 = formattedString.Split('-');
Note that this only applies to the presented example with an assumption. Any reverse algorithm is dependent on the kind of formatting employed; an inverse operation may not even be possible, as noted by the other answers.
A simple solution might be to
replace all format tokens with (.*)
escape all other special charaters in format
make the regex match non-greedy
This would resolve the ambiguities to the shortest possible match.
(I'm not good at RegEx, so please correct me, folks :))
After formatting, you can put the resulting string and the array of objects into a dictionary with the string as key:
Dictionary<string,string []> unFormatLookup = new Dictionary<string,string []>
...
var arr = new string [] {"asdf", "qwer" };
var res = string.Format(format, arr);
unFormatLookup.Add(res,arr);
and in Unformat method, you can simply pass a string and look up that string and return the array used:
string [] Unformat(string res)
{
string [] arr;
unFormatLoopup.TryGetValue(res,out arr); //you can also check the return value of TryGetValue and throw an exception if the input string is not in.
return arr;
}