Cannot implicitly convert string[][] to string[] in C# - c#

I'm getting this error in new keyword.
//Code:
public static string[] SplitStrings(string inboundString, char splitChar)
{
if(inboundString.Contains(splitChar))
{
return new[] { inboundString.Split(splitChar) };
}
}

You don't need to create a new array the return from split works just fine.
public static string[] SplitStrings(string inboundString, char splitChar)
{
if(inboundString.Contains(splitChar))
{
return inboundString.Split(splitChar);
}
else
{
return new string[] {};
}
}

Try it like this
public static string[] SplitStrings(string inboundString, char splitChar)
{
return inboundString.Split(splitChar);
}
String.Split itself returns a string[] so you don`t need to initialize a new one.

Related

Can you get a value in a structure through an outside variable in C#?

So, I am kind of used to structuring things like JavaScript and in light of that I do struggle in some areas in C#. Right now I'm trying to use structures in a way I can call a value using a variable that would match the value I'm going for.
For example my structure would be this:
public struct test
{
public int[] valuesOne;
public int[] valuesTwo;
public test(int[] data)
{
valuesOne = new int[2] { data[0], data[1] };
valuesTwo = new int[2] { data[2], data[3] };
}
}
Okay so say I have all of this and I want to get test.valuesOne[0] but from a variable like so:
string getValue = "valuesOne";
Console.Log(test[getValue][0]);
I know this provides a indexing error, but I'm in a situation where I kind of want this functionality. Sure I can pass my structure through a simple method, but if I can do it in a similar way to this without a huge problem I'd like to.
c# and JavaScript are two different pairs of shoes.
I try to do something similar as your code, however not sure if that's what you're looking for.
class Program
{
static void Main(string[] args)
{
var t = new Test(new int[] { 1, 2, 3, 4 });
var value = t["valueOne"][0];
Console.WriteLine(value);
}
}
public class Test
{
private Dictionary<string, int[]> _data = new Dictionary<string, int[]>();
public Test(int[] data)
{
_data.Add("valueOne", new int[] { data[0], data[1]});
_data.Add("valueTwo", new int[] { data[2], data[3]});
}
public int[] this [string value]
{
get { return _data[value]; }
}
}
you can use dynamic + reflection + this[string key] to do it. but it needs some extra code.
note :
it's a bad idea,this will lose the advantage of strong type checking.
demo :
void Main()
{
var test = new test(new[] {1,2,3,4,5});
Console.WriteLine( test["valuesOne"][0] ); //1
Console.WriteLine( test["valuesTwo"][1] ); //4
}
public struct test
{
public int[] valuesOne;
public int[] valuesTwo;
public test(int[] data)
{
valuesOne = new int[2] { data[0], data[1] };
valuesTwo = new int[2] { data[2], data[3] };
}
public dynamic this[string key]
{
get
{
return this.GetFieldValue(key);
}
}
}
public static class Extension
{
public static object GetFieldValue(this object t, string fieldName)
{
var type = t.GetType();
var fields = type.GetFields();
var field = fields.Single(pi => pi.Name == fieldName);
return field.GetValue(t);
}
}
online demo link : can-you-get-a-value-in-a-structure-through-an-outside-variable-in-c | .NET Fiddle
Usually I too would recommend using a Dictionary as in #gsharp's answer. But since that isn't an option for you, perhaps you could go with a Dictionary of delegates instead:
var accessor = new Dictionary<string, Func<test, int[]>>
{
{ nameof(test.valuesOne), x => x.valuesOne },
{ nameof(test.valuesTwo), x => x.valuesTwo }
};
Now you can access your data like so:
string getValue = "valuesOne";
Console.Log(accessor[getValue](test_instance)[0]);
You can extend this concept by wrapping this Dictionary into an Extension Method:
public static class Extensions
{
private static new Dictionary<string, Func<test, int[]>> accessor =
new Dictionary<string, Func<test, int[]>>
{
{ nameof(test.valuesOne), x => x.valuesOne },
{ nameof(test.valuesTwo), x => x.valuesTwo }
};
public static int[] Property(this test t, string name)
{
return accessor[name](t);
}
}
Then you can write:
Console.Log(test_instance.Property(getValue)[0]);

How to get string array values, i.e. passed as a parameter in an object array?

I am trying to pass string array and other parameters in an object array,and on other side I want to retrieve this parameter values and display them, but I am not able to retrieve the string array values,rather it displays the type of the string array.
static void Main(string[] args)
{
string[] test = {"t1","t2","t3"};
TestArray(1,test,"Hello");
}
static void TestArray(params object[] array)
{
foreach(var value in array)
{
Console.WriteLine(value);
}
Console.ReadLine();
}
You're printing all values as string. Array.ToString() will return $elementType[], so System.String[] in your case.
You'll need to test if value is an IEnumerable, and if so, iterate over it and print its members' values, recursively.
static void TestArray(params object[] array)
{
PrintValue(value);
}
public void PrintValue(object value)
{
var enumerable = value as IEnumerable;
if (enumerable != null)
{
foreach (var subvalue in enumerable)
{
PrintValue(subvalue);
}
}
else
{
Console.WriteLine(value.ToString());
}
}
Do note that this still can't print complex types, and in that case, will just output its type name again.
Try this:
static void Main(string[] args)
{
string[] test = { "t1", "t2", "t3" };
TestArray(1, test, "Hello");
}
static void TestArray(params object[] array)
{
foreach (var value in array)
{
if (value is IEnumerable<object>)
foreach (var element in value as IEnumerable<object>)
Console.WriteLine(element);
else
Console.WriteLine(value);
}
Console.ReadLine();
}
You have to check if the value is an array and loop over it:
public static void DisplayParams(params object[] parameters)
{
foreach(var param in parameters)
{
var arr = param as string[];
if( arr != null)
{
foreach(var value in arr)
{
Console.WriteLine( value );
}
}
else
{
Console.WriteLine( param );
}
}
}
This part:
var arr = p as string[];
if( arr != null)
will check if its an array and will loop over it when it is.
Of course when you insert other types this won't work, so some validation would be wise
One option to consider:
static void Main(string[] args)
{
string[] test = { "t1", "t2", "t3" };
List<object> combined = new List<object> {1};
combined.AddRange(test);
combined.Add("Hello");
TestArray(combined.ToArray());
}
static void TestArray(params object[] array)
{
foreach (var value in array)
{
Console.WriteLine(value);
}
Console.ReadLine();
}
In short, you merge all the values into a single array before passing that array into the method.
If you went this route, consider removing the params keyword - so it makes it literally impossible for someone to call it the original way you had it. It forces them to think about how they want IEnumerables to be handled.

Regex combine more than 1 function

How can I call 2 functions in my code for one string?
public static string ecleaner(string str)
{
return Regex.Replace(str, "[éèê]+", "e", RegexOptions.Compiled);
}
public static string acleaner(string str)
{
return Regex.Replace(str, "[áàâ]+", "a", RegexOptions.Compiled);
}
Now I want to check the word "Téèááést" ,after this it should look like Teaest .
You could use a MatchEvaluator delegate, like this:
public static string cleaner(string str)
{
return Regex.Replace(str, "(?<a>[áàâ]+)|(?<e>[éèê]+)", onMatch, RegexOptions.Compiled);
}
private static string onMatch(Match m)
{
if (m.Groups["a"].Success)
return "a";
if (m.Groups["e"].Success)
return "e";
return "";
}
Or alternatively:
public static string cleaner(string str)
{
var groups = new[] { "a", "e" };
return Regex.Replace(str, "(?<a>[áàâ]+)|(?<e>[éèê]+)", m => groups.First(g => m.Groups[g].Success), RegexOptions.Compiled);
}
Did you try this?
string str = "Téèááést";
str = ecleaner(str);
str = acleaner(str);
public static class StringExtensions
{
public static string ecleaner(this string str)
{
return Regex.Replace(str, "[éèê]+", "e", RegexOptions.Compiled);
}
public static string acleaner(this string str)
{
return Regex.Replace(str, "[áàâ]+", "a", RegexOptions.Compiled);
}
}
//...
var result = "Téèááést".ecleaner().acleaner();
You could also combine an extension method class with #p.s.w.g's answer, to make things even neater.

Function having 2 array as input parameter and 2 as output?

Can I create a function C# which has 2 arrays as input parameter and 2 as output?
A method can only have one return value; however, you can use out parameters to return multiple results.
void MyFunction(int[] input1, int[] input2, out int[] output1, out int[] output2)
Use Tuple :
public Tuple<Object[], Object[]> FunctionName(Object[] array1, Object[] array2)
{
//Your code
return new Tuple<Object[],Object[]>({},{});
}
void YourFunc(Int32[] input1, Int32[] input2, out Int32[] output1, out Int32[] output2)
{
output1 = new Int32[] { 1, 2, 3 };
output2 = new Int32[] { 4, 5, 6 };
}
…
YourFunc(i1, i2, out o1, out o2);
You sure can, buddy!
public ArrayGroup MyFunction(myType[] firstArg, myType[] secondArg) {
ArrayGroup result = new ArrayGroup();
/*Do things which fill result.ArrayOne and result.ArrayTwo */
return ArrayGroup;
}
class ArrayGroup {
myType[] ArrayOne { get; set;}
myType[] ArrayTwo { get; set;}
}
Fill in myType with whatever types you want the arrays to be! Like string or int or a complex type!
Sure you can, start with a container for the response:
public class Response
{
public string[] One{get;set;}
public string[] Two{get;set;}
}
And your method might look like
public Response DoSomething(string[] inputOne, string[] inputTwo)
{
// do some thing interesting
return new Respponse
{
One = new string[]{"Hello","World"},
Two = new string[]{"Goodbye","Cruel","World"},
}
}
Option one: Create a type holding the result:
SomeResult MyFunction(T[] arr1, T[] arr2)
{
// ..
return new SomeResult(r1, r2);
}
class SomeResult
{
public SomeResult(T[] a, T[] b) { /* .. */ }
// Rest of implementation...
}
Option two: Return a tuple:
Tuple<T[], T[]> MyFunction(T[] arr1, T[] arr2) { }
Option three: Use out parameters (don't do this):
void MyFunction(T1[] arr1, T[] arr2, out T[] result1, out T[] result2) { }
I prefer option one, and recommend against using out parameters. If the two arguments are of the same type but not interchangeable I'd recommend also creating a type for the argument to make it a single argument function with a single result.
yes you can do this!
You need to pass two output arrays as a reference to the function.
Here is the code example.
Function
private bool ArrayImp(string[] pArray1, string[] pArray2, ref string[] oArray1, ref string oArray2)
{
//Do your work here
//Here oArray1 and oArray2 are passed by reference so you can directly fill them
// and get back as a output.
}
Function Call
string[] iArray1 = null;
string[] iArray2 = null;
string[] oArray1 = null;
string[] oArray2 = null;
ArrayImp(iArray1, iArray2, oArray1, oArray2);
Here you need to pass iArray1 and iArray2 as input array and you will get oArray1 and oArray2 as output.
Cheeerss!! Happy Coding!!
You can pass 2 arrays as parameters to a function, but the function can return a single thing. So you could create an object with the two arrays you need to return, and return that object.

How do I find the index of an undefined string in a List<T>

It's my understanding that if I want to get the ID of an item in a list, I can do this:
private static void a()
{
List<string> list = new List<string> {"Box", "Gate", "Car"};
Predicate<string> predicate = new Predicate<string>(getBoxId);
int boxId = list.FindIndex(predicate);
}
private static bool getBoxId(string item)
{
return (item == "box");
}
But what if I want to make the comparison dynamic? So instead of checking if item=="box", I want to pass in a user-entered string to the delegate, and check if item==searchString.
Using a compiler-generated closure via an anonymous method or lambda is a good way to use a custom value in a predicate expression.
private static void findMyString(string str)
{
List<string> list = new List<string> {"Box", "Gate", "Car"};
int boxId = list.FindIndex(s => s == str);
}
If you're using .NET 2.0 (no lambda), this will work as well:
private static void findMyString(string str)
{
List<string> list = new List<string> {"Box", "Gate", "Car"};
int boxId = list.FindIndex(delegate (string s) { return s == str; });
}
You can just do
string item = "Car";
...
int itemId = list.FindIndex(a=>a == item);
string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
List <string> list= new List<string>("Box", "Gate", "Car");
string SearchStr ="Box";
int BoxId= 0;
foreach (string SearchString in list)
{
if (str == SearchString)
{
BoxId= list.IndexOf(str);
break;
}
}

Categories