I have a two dimensional array declared. It has two columns - filename and batch. I initialize it empty.
string[,] a_Reports = new string[,] { { "", "" } };
I have some code that resizes it and populates it. Everything is a string value. When I go to look up an element in the array like so:
int value1 = Array.Find<string>(a_Reports, element=>element.Equals(newFileName));
I get the error:
CS1503 Argument 1: cannot convert from 'string[*,*]' to 'string[]'
I've tried it every which way and nothing works. Please help me!!! I've spent hours on it already.
Array.Find is only for one-dimensional arrays. (MSDN)
Check out this answer on 'How do I search a multi-dimensional array?'
Produce a similar extension method, like in my example on rextester.
Or use a jagged array instead of a two-dimensional one and a combination of foreach and find, like:
string[][] jagged = ...
Array.ForEach(jagged, array=>Array.Find(array, x=>x=="" ));
Related
I'm a little bit confused. I try to assign a string array to a two dimensional string array. But get "Wrong number of indices" error.
I understand the error, but should it not be possible to assign an array to the second dimension array field?
As sortedString has x number of fields with each an string array, should it not be possible to assign an string array to just a indexed field? (as the s.Split(';') already creates an array)
string[,] sortedString = new string[count,columns];
sortedString[counter] = s.Split(';');
You're confusing a multidimensional array with a jagged array. sortedString is a 2-dimensional array of type string, so you must always provide the correct number of indices - in this case, 2. You can't say sortedString[x], you can only say sortedString[x, y].
You're probably thinking of a jagged array - i.e., a single-dimensional array, where each element is itself a (usually single-dimensional) array. Declare sortedString like this:
string[][] sortedString = new string[count][];
This will allow each "inner" array to be of a different length (depending on how many ; there are in each s), which might not be what you want.
C# has two kinds of 2D arrays. If you need access to one dimension at a time as it's own array, you must use the "jagged" variety, like this:
string[][] sortedString = new string[count][];
for(int i = 0; i<sortedString.Length;i++)
sortedString[i] = new string[columns];
Or, even better:
var sortedString = new List<string[]>;
I just got thrown into a C# project for solidWorks that I'm not too comfortable with. I need to convert this out System.Array to a string[]. Then that string is called and converted from out System.Array to out EdmLib.EdmBatchError2[].
TLDR: out System.Array' to a string[].
Code:
private void GetSerialNumberGenerators()
{
IEdmSerNoGen7 utility = this.m_vault.CreateUtility(EdmUtility.EdmUtil_SerNoGen) as IEdmSerNoGen7;
Array ppoRetNames = Array.CreateInstance(typeof(string[]), 0);
utility.GetSerialNumberNames(out ppoRetNames);
this.comboBoxSerialNumber.DataSource = (object) ppoRetNames;
}
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'out System.Array' to 'out string[]'
It's simple as
string[] ppoRetNames;
GetSerialNumberNames(out ppoRetNames);
This is the way to declare a string[]. Don't initialize it yourself because GetSerialNumberNames will do it (out-parameter). No need to use Array.CreateInstance.
Apart from that you are creating a jagged array because you pass typeof(string[]) not typeof(string). You need a one dimensional array so this would be correct:
Array someArray = Array.CreateInstance(typeof(string), 0);
string[] ppoRetNames = (string[])someArray; // so a cast is what was missing
GetSerialNumberNames returns System.Array of type EdmBatchError2, which is a structure of 4 ints, so I don't know how that would cast to a string[] in a usable sense. Here is what I do:
utility.GetSerialNumberNames(out Array ppoRetNames);
foreach(EdmBatchError2 batchError in ppoRetNames) {
// construct error message with below variables for each error
//batchError.mlFileID;
//batchError.mlFolderID;
//batchError.mlVariableID;
//batchError.mlErrorCode;
}
This question already has answers here:
Two dimensional array slice in C#
(3 answers)
Closed 8 years ago.
Following situation:
I have a Array which got 2 dimension. No i want to access the second dimension. How can i achieve this goal?
Here my code to clarify my problem:
private static int[,] _Spielfeld = new int[_Hoehe, _Breite];
private static bool IstGewonnen(int spieler)
{
bool istGewonnen = false;
for (int zaehler = 0; zaehler < _Spielfeld.GetLength(0); zaehler++)
{
//Here i cant understand why compiler doesnt allow
//Want to give the second dimension on the Method
istGewonnen = ZeileSpalteAufGewinnPruefen(_Spielfeld[zaehler] ,spieler);
}
return istGewonnen;
}
//This method want to become an Array
private static bool ZeileSpalteAufGewinnPruefen(int[] zeileSpalte, int spieler)
{
//Some further code
}
The compiler is saying: "Argument from type int[,] is not assignable to argument of type int[]. In Java it is working as i expected. Thanks in advance.
Define your array as a jagged array (array of arrays):
private static int[][] _Spielfeld = new int[10][];
Then loop through the first dimension and initialize.
for (int i = 0; i < _Spielfeld.Length; i++)
{
_Spielfeld[i] = new int[20];
}
Then the rest of your code will compile OK.
C# allows two different offers two flavors of multidimensional arrays which, although they look quite similar, handle quite differently in practice.
What you have there is a true multidimensional array, from which you cannot automatically extract a slice. That would be possible (as in Java) if you had a jagged array instead.
If the choice of having a multidimensional array is deliberate and mandatory then you will have to extract slices manually; for example see this question.
If the choice between jagged and multidimensional is open then you can also consider switching to a jagged array and getting the option of slicing for free.
When using the .ToArray() function is it necessary to implicitly define the size of the array in order to hold of the characters that were in the list you're converting?
String [] array = List.ToArray();
I tried doing this because I needed to use the .GetValue() ability of the array, however, the array is maintaining a size of 1 and not holding the material from the list. Am I trying to use the .ToArray() incorrectly?
colAndDelimiter = new List<string>();
colAndDelimiter.Add(text);
String [] cd = colAndDelimiter.ToArray();
This is all of the code I have that effects the array. When I Console.WriteLine() the list it gives me the entirety of the text. I may be confused about how list works. Is it storing everything as a single item, and that's why the array only shows one place?
You don't need to convert it to an array to get specific characters out.
Just use text[index] to get at the needed character.
If you really need it as an array, use String.ToCharArray() - you want an array of char not an array of string.
Edit:
Is it storing everything as a single item, and that's why the array only shows one place?
Yes, yes it is. You're making a list of strings which contains one string: the entire contents of text - what it seems that you want is to split it up letter by letter, which is what the above methods will achieve.
It should work fine, but try the var operator to be sure.
var array = List.ToArray();
Is there a reason to use Array.GetValue instead of the built in functions of the List<T> itself
EG:
string value = List.ElementAt(1);
var values = List.GetRange(0, 5);
What you are doing is fine.. but lets say that you are not sure of the size of the
string[] cd then you can do something like the following
var colAndDelimiter = new List<string>();
colAndDelimiter.Add(text);
String[] cd = { };
cd = colAndDelimiter.ToArray();
find the position of the data in cd
string value = cd[0];
Update:
If you want to do this based on values being stored in a single line then you can do this without having to declare the cd variable as string[] cd;
var colAndDelimiter = new List<string>();
colAndDelimiter.Add("Hello, World, Week, Tuesday");
var cd = colAndDelimiter[0].Split(',');
As long as your List object is some IEnumerable (or similar) that has items in it, this should indeed convert your List to an Array.
Note that once you have created this array, adding elements to List won't also add it to the Array
I use this code to get a String array of headings used in a MS Word 2007 document (.docx):
dynamic arr = Document.GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
Using the debugger, I see that arr is dynamically assigned a String array with titles of all my headings in the document (about 40 entries). So far so good.
Then, I want to access the strings, but no matter how I do it, I get the following exception:
InvalidCastException:
Unable to cast object of type 'System.String[*]' to type 'System.String[]'.
I have tried different ways of accessing the strings:
By index:
String arr_elem = arr[1];
By casting to an IEnumerable:
IEnumerable list = (IEnumerable)arr;
By using a simple foreach loop:
foreach (String str in arr)
{
Console.WriteLine(str);
}
However, no matter what I try, I always end up with the same exception as shown above.
Can anyone explain what I am missing here / what I am doing wrong? And especially String[*] - what does it mean?
string[] is a vector - a 1-d, 0-based array. string[*], however, is a regular array that just happens to have one dimension. Basically, you are going to have to handle it as Array, and either copy the data out, or use the Array API rather than the string[] API.
This is the same as the difference between typeof(string).MakeArrayType() (the vector) and typeof(string).MakeArrayType(1) (a 1-d non-vector).
try
object arr_r = Document.GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
Array arr = ((Array) (arr_r));
string myHeading = (string) arr.GetValue(1);
The problem is that you're using dynamic in a situation where it apparently wasn't intended. When the dynamic runtime sees a 1D array, it assumes a vector, and tries to index into it or enumerate it as if it were a vector. This is one of those rare cases where you have a 1D array that is not a vector, so you have to handle it as an Array:
Array arr = (Array)(object)Document.
GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
// works
String arr_elem = arr.GetValue(1);
// now works
IEnumerable list = (IEnumerable)arr;
// now works
foreach (String str in arr)
{
Console.WriteLine(str);
}