Hello I need to take string item from string list and a add it to the int array i trying like this but its writing me error Cannot implicity convert type int to int[]
but in for sequence i adding only one int to one item in array so what is wrong please
private void buttonGenerateO_Click(object sender, EventArgs e)
{
List<string> AgentNumbers = new List<string>();
List<string> AgentRide = new List<string>();
int pocet = AgentNumbers.Count;
int[][] dvouRozmernePole = new int[2][];
dvouRozmernePole[0] = new int[pocet];
dvouRozmernePole[1] = new int[pocet];
foreach (string AgeNumb in AgentNumbers)
{
for (int i = 0; i < dvouRozmernePole[0].Length; i++)
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
}
foreach (string AgeRide in AgentRide)
{
for (int i = 0; i < dvouRozmernePole[1].Length; i++)
dvouRozmernePole[i] = Convert.ToInt32(AgeRide);
}
Look at this declaration:
int[][] dvouRozmernePole = new int[2][];
So dvouRozmernePole is an array of arrays. Now look here:
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
You're trying to assign an int value to dvouRozmernePole[i], which you can't do because it should be an int[].
I suspect you want:
dvouRozmernePole[0][i] = Convert.ToInt32(AgeNumb);
Having said that, given these lines:
List<string> AgentNumbers = new List<string>();
List<string> AgentRide = new List<string>();
int pocet = AgentNumbers.Count;
int[][] dvouRozmernePole = new int[2][];
dvouRozmernePole[0] = new int[pocet];
dvouRozmernePole[1] = new int[pocet];
... you'll always have empty lists anyway, so there are no values to convert.
Do you really need to use arrays at all? Using List<T> everywhere would almost certainly be simpler.
LINQ can also make this simpler. For example:
int[] numbers = AgentNumbers.Select(x => int.Parse(x)).ToArray();
int[] rides = AgentRide.Select(x => int.Parse(x)).ToArray();
int[][] dvouRozmernePole = { numbers, rides };
dvouRozmernePole is an array of int[], while Convert.ToInt32 returns an int. Therefore in:
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
dvouRozmernePole[i] is an int[], and you are trying to assign an int.
It looks like you want:
dvouRozmernePole[0][i] = Convert.ToInt32(AgeNumb);
and later
dvouRozmernePole[1][i] = Convert.ToInt32(AgeRide);
You could instead do:
int[][] dvouRozmernePole = new int[2][]
{
AgentNumbers.Select(num => Convert.ToInt32(num)).ToArray(),
AgentRide.Select(ride => Convert.ToInt32(ride)).ToArray()
};
to initialise the array.
The error is quite clear. In the statement
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
you assign an integer to an array.
dvouRozmernePole is an array of array of ints
so dvouRozmernePole[i] expects and int[] rather than the int value
try
did you mean
for (int i = 0; i < dvouRozmernePole[0].Length; i++)
dvouRozmernePole[0][i] = Convert.ToInt32(AgeNumb);
}
foreach (string AgeRide in AgentRide)
{
for (int i = 0; i < dvouRozmernePole[1].Length; i++)
dvouRozmernePole[1][i] = Convert.ToInt32(AgeRide);
}
Related
I want to implement 'string[] loadedText' into 'string[] dataList', but I keep getting an error saying "Cannot implicitly convert type 'string[]' to 'string'".
string[] dataList = new string[1800];
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
string[] loadedData = loadNewData.ReadLine().Split(';');
dataList[i] = loadedData;
i++;
}
I need the 'dataList' array that will contain 1800 'loadedData' arrays which contain 4 strings in them.
What you need is a jagged array:
string[][] dataList = new string[1800][];
loadNewData.ReadLine().Split(';'); returns array of string and you are storing array of strings into dataList[i] i.e. string element of string array. This is the reason behind error which you mentioned in your question
If you want to store loadNewData.ReadLine().Split(';'); into an array then I would suggest you to use nested list List<List<string>>
Something like,
List<List<string>> dataList = List<List<string>>();
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
var innerList = loadNewData.ReadLine().Split(';').ToList();
dataList.Add(innerList);
i++;
}
It seems you need an array of array of strings, something like string[][].
You can do it like this:
string[][] dataList = new string[1800][];
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
string[] loadedData = loadNewData.ReadLine().Split(';');
dataList[i] = loadedData;
i++;
}
As you are splitting loadedNewData, you receive string[] already, because Split() function returns string[].
there are 350 elements in my arraylist , each of it consist of an array of 9 integers i-e Count of each element is 9 . i want to retrievere each of it.
here is what i am trying but giving me
error
"Unable to cast object of type
'System.Collections.Generic.List`1[System.Int32]' to type
'System.Int32[]'."
FileName = "E:\\Normalized_sheet1.txt";
FileStream Fs = File.OpenRead(FileName);
StreamReader SR = new StreamReader(Fs);
while (!SR.EndOfStream)
{
Line = SR.ReadLine().Split('\t'); //make an array of text each time
List<string> arr = new List<string>();
arr.AddRange(Line);
List<int> intList = arr.ConvertAll(s => Int32.Parse(s));
myvalues.Add(intList);
}
SR.Close();
Fs.Close();
for (i = 0; i < Samples; i++)
{
InputParameter=(int[]) myvalues[i]; // Error
}
myvalues.Add(intList.ToArray());
Because you mentioned that you have a list of arrays. If it's a List<int[]> then you can't add lists to it - you can only add arrays. ToArray() returns an array of the items in your list.
If "myvalues" is a List of int[] then your loop should look like this:
for (i = 0; i < Samples; i++)
{
InputParameter= myvalues[i]; //don't need cast.
}
if myvalues is a List of List of int, then your code should be:
for (i = 0; i < Samples; i++)
{
InputParameter= myvalues[i].ToArray();
}
Do not cast, use the appropriate List method:
InputParameter=myvalues[i].ToArray();
I have an Array with Category Names, but now i Need to assign a few Counters to each Category.
Is there a way to expand my 1D-Array to a 2D-Array in C#?
Thanks for helping!
Edit:
PerformanceCounterCategory[] categories;
categories = PerformanceCounterCategory.GetCategories();
string[] categoryNames = new string[categories.Length];
string[] categoryNames_en = new string[categories.Length];
for (int objX = 0; objX < categories.Length; objX++)
{
categoryNames[objX] = categories[objX].CategoryName;
}
Array.Sort(categoryNames);
for (int objX = 0; objX < categories.Length; objX++)
{
Console.WriteLine("{0,4} - {1}", objX + 1, categoryNames[objX]);
}
I have the Array categoryNames with all the Names of the Categories, but in every Category there are a few Counters which i want to assign to their Category somehow...
Unfortunately you can't use Array.Copy since the source and destination array do not have the same dimensions.
Furthermore, you can't expand arrays in C#, since they are initialized with a fixed size.
What you can do is create a new array with a second dimonesion and copy the values over and set the second dimension to a default value.
void Main()
{
int[] sourceCollection = new [] {1,2,3,4,5,6,7} ;
var result = CopyArrayValues(sourceCollection, 2);
result.Dump();
}
//create a new 2d array
T[,] CopyArrayValues<T>(T[] DataSource, int SecondLength)
{
//Initialize the new array
var Target = new T[DataSource.Length, SecondLength];
//Copy values over
for (int i = 0; i < DataSource.Length; i++)
{
Target[i, 0] = DataSource[i];
}
return Target;
}
Output:
If it's ok for you to have array of arrays, you can do something along this pattern:
int[] sourceCollection = new[] { 1, 2, 3, 4, 5, 6, 7 };
int[][] arr = sourceCollection.Select(i => Enumerable.Range(i, 4).ToArray()).ToArray();
I want to remove the element form the array. Actually I don't know the the index of the element and want to remove through it's value. I have tried a lot but fail. This is the function which i used to add element in the Array
string [] Arr;
int i = 0;
public void AddTOList(string ItemName)
{
Arr[i] = ItemName;
i++;
}
And I want to remove the element by the value. I know the below function is wrong but I want to explain what I want:
public void RemoveFromList(string ItemName)
{
A["Some_String"] = null;
}
Thanks
If you want to remove items by a string key then use a Dictionary
var d = new Dictionary<string, int>();
d.Add("Key1", 3);
int t = d["Key1"];
Or something like that.
Array has a fixed size, which is not suitable for your requirement. Instead you can use List<string>.
List<string> myList = new List<string>();
//add an item
myList.Add("hi");
//remove an item by its value
myList.Remove("hi");
List<string> list = new List<string>(A);
list.Remove(ItemName);
A = list.ToArray();
and #see Array.Resize
and #see Array.IndexOf
You can iterate through every value in array and if found then remove it. Something like this
string[] arr = new string[] { "apple", "ball", "cat", "dog", "elephant", "fan", "goat", "hat" };
string itemToRemove = "fan";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == itemToRemove)
{
arr[i]=null;
break;
}
}
I want to create array 10 * 10 * 10 in C# like int[][][] (not int[,,]).
I can write code:
int[][][] count = new int[10][][];
for (int i = 0; i < 10; i++)
{
count[i] = new int[10][];
for (int j = 0; j < 10; j++)
count[i][j] = new int[10];
}
but I am looking for a more beautiful way for it. May be something like that:
int[][][] count = new int[10][10][10];
int[][][] my3DArray = CreateJaggedArray<int[][][]>(1, 2, 3);
using
static T CreateJaggedArray<T>(params int[] lengths)
{
return (T)InitializeJaggedArray(typeof(T).GetElementType(), 0, lengths);
}
static object InitializeJaggedArray(Type type, int index, int[] lengths)
{
Array array = Array.CreateInstance(type, lengths[index]);
Type elementType = type.GetElementType();
if (elementType != null)
{
for (int i = 0; i < lengths[index]; i++)
{
array.SetValue(
InitializeJaggedArray(elementType, index + 1, lengths), i);
}
}
return array;
}
You could try this:
int[][][] data =
{
new[]
{
new[] {1,2,3}
},
new[]
{
new[] {1,2,3}
}
};
Or with no explicit values:
int[][][] data =
{
new[]
{
Enumerable.Range(1, 100).ToArray()
},
new[]
{
Enumerable.Range(2, 100).ToArray()
}
};
There is no built in way to create an array and create all elements in it, so it's not going to be even close to how simple you would want it to be. It's going to be as much work as it really is.
You can make a method for creating an array and all objects in it:
public static T[] CreateArray<T>(int cnt, Func<T> itemCreator) {
T[] result = new T[cnt];
for (int i = 0; i < result.Length; i++) {
result[i] = itemCreator();
}
return result;
}
Then you can use that to create a three level jagged array:
int[][][] count = CreateArray<int[][]>(10, () => CreateArray<int[]>(10, () => new int[10]));
With a little help from Linq
int[][][] count = new int[10].Select(x => new int[10].Select(x => new int[10]).ToArray()).ToArray();
It sure isn't pretty and probably not fast but it's a one-liner.
There is no 'more elegant' way than writing the 2 for-loops. That is why they are called 'jagged', the sizes of each sub-array can vary.
But that leaves the question: why not use the [,,] version?
int[][][] count = Array.ConvertAll(new bool[10], x =>
Array.ConvertAll(new bool[10], y => new int[10]));
A three dimensional array sounds like a good case for creating your own Class. Being object oriented can be beautiful.
You could use a dataset with identical datatables. That could behave like a 3D object (xyz = row, column, table)... But you're going to end up with something big no matter what you do; you still have to account for 1000 items.
Why don't you try this?
int[,,] count = new int[10, 10, 10]; // Multi-dimentional array.
Any problem you see with this kind of representation??