Passing dynamic arrays into the argument - c#

I have a class constructor accepting params T[][] arrays.
public CartesianProduct(params T[][] arrays)
{
}
I am passing the arrays below which is working fine
string[] arr1 = { "MSG1" };
string[] arr2 = { "OFFER1", "OFFER2" };
string[] arr3 = { "CTA1", "CTA2" };
var cross = new CartesianProduct<string>(arr1,arr2,arr3);
This works fine if i know the number of arrays and then pass it in the argument. The problem is when i am creating a button in the windows form to add new arrays. For example i have a simple text box and a button which creates an array. Click Add new array will create another array. How can i pass these arrays in the argument? Help would be appreciated . Thanks in advance

You can not dynamically add a 4th parameter to the call. You can dynamically create an array containing an arbitrary number of other arrays and pass that:
var aList = new List<string[]>();
aList.Add(arr1);
//...
var cross = new CartesianProduct<string>(aList.ToArray());
You may consider adding another constructor that accepts a List directly.

Related

How to pass the elements in Array from a list to a List? c#

Pre-information
-User inputs data in console
-Save data in an Array of 2 elements[2]
-Save the Array with 2 elements in a LIST
*Now what i try to achieve is that the user can check if search is in the list regardless if its written in lower or upper case.
List<string[]>MyList = new List<string[]>();
var[] myArray = new [] { "A", "B" };
MyList.Add(myArray);
int y = 0;
Console.WriteLine("Inpu what you are Searching For: ");
string serchString = Console.ReadLine();
serchString = serchString.ToLower();
for (int i = 0; i < MyList.Count; i++)
{
List<object> oneTimeList = new List<object>();
oneTimeList.AddRange(myList[i]);
Console.WriteLine(oneTimeList);
if (MyList[i].Contains(serchString.ToLower()))
{
Console.WriteLine("Yes you have added this");
}
else if (!myList[i].Contains(serchString))
{
y += 1;
}
}
if (y == myList.Count)
{
Console.WriteLine("You Have not entered this Yet");
}
My logic(maybe not the best in the planet :P) says that i have to make a comparison of all the elements of the array in turn with the search the user made and if its true continue, And in order to make this i need first to get the information of the arrays of the list and convert them to a list and then convert them to lowercase.
Every thing goes fine until the part where i try to add the Arrays to the List and all i am adding are Arrays[].
Any Suggestion on how to approach this issue or how to pass the elements of an ARRAY that is inside of a LIST to a NEW LIST?
It sounds like to want to take an array of strings (assumed as you mention lower casing it), add them all to a list, lower-case them and then compare?
This being the case you don't need to do any of that. You can simply do:
var myArray = new [] { "A", "B", "C" }
var toCheck = "a";
//Use the IEnumerable<T>.Contains() Linq extension
if (myArray.Contains(toCheck, StringComparer.OrdinalIgnoreCase))
{
//...
}
If you really want to add them to a list I can't give you an example using your code, but to "pass elements of an array to a new list" you can do any of the following:
//List<T>(IEnumerable<string>) constructor
var newList = new List<string>(myListOfStrings);
//List<T>.AddRange(IEnumerable<string>)
var newList = new List<string>();
newList.AddRange(myListOfStrings);
//List<T>.Add(T) (adding items one at a time)
var newList = new List<string>();
newList.Add(myListOfStrings[index]);
It's worth noting here as well that any of the above references to myListOfStrings could be an array of strings (string[]) or a list of strings (List<string>) because they both implement IEnumerable<string> which is the type the above methods require (except for Add which wants a single item).
Here is the documentation for List that describes in details how to use each of the above (and all other other available methods...)

c # - copying elements of one array to another - compile error

Learning some basics.. I'm trying to copy elements of an array to another. Let's say I don't know the size of the array 'bar'. So, I create an empty array 'arr' to copy the elements to bar into. The code below doesn't work.
It works if I replace
string[] arr ={} to string[] arr ={"",""}
How to declare an empty array and what should I modify in my code to achieve my goal?
Thanks!
//code
string[] bar = {"test", "user"};
string[] arr = {};
//iterate from the first to the last element of array bar
for (int i =0;i<bar.Length-1;i++)
{
Console.WriteLine("copy");
//copy string from bar to arr
arr[i]= bar[i];
//display the copied content from new array
Console.WriteLine(arr[i]);
}
in C#, arrays are of a fixed size. So when you create your array with size 0, you can't change the number of items it will contain, without re-instantiating it.
If you want to use a collection you can actively add/remove from (as is very common), consider using a List<T>:
string[] bar = {"test", "user"};
List<string> list = new List<string>();
for (int i =0;i<bar.Length-1;i++)
{
list.Add(bar[i]);
Console.WriteLine(list[i]);
}
By string[] arr = {}; you're instantiating an empty array of ZERO length, thus you need to define it like string[] arr = string[bar.Length];.
UPD:
Your code worked with string[] arr = {"",""}, because in this case you defined an array of length 2 using a two empty strings, but that's a code smell.
Arrays are fixed in size, which is why things like Lists are preferred over them.
In the case where you change your array definition to: string[] arr ={"",""} you are defining an array with a size of 2, same as your original array. When you try to copy it, the compiler already has everything allocated and ready to go, so it knows where position 0 and position 1 are in the array arr.
In the example in your code, where you have the array defined by string[] arr = {}; you are giving it an empty array (array size 0). The compiler has an issue, because it cannot reference position 0 or position 1 on an array that is empty.
You can modify the line as:
string[] arr = new string[4];
or
List<string> arr = new List<string>();
If you're going to use arrays, you'll want to create the second array as the same size as the first.
string[] bar = {"test", "user"};
string[] arr = new string[bar.Length];
If you know ahead of time that your array will be two, then you can just create it to be size two. Otherwise you'll want to inspect the size of the array you're copying from. If you know that you'll be adding and/or removing items, you'll want to use a different collection.

Passing array between forms and managing in arrays

I want to transfer an array from Form1 to Form2, then on Form2 add some values to the array.
On Form1 button click I put this code:
int[] arrayOfInt = new int[4];
arrayOfInt[0] = 19;
arrayOfInt[1] = 12;
Form2 frm2 = new Form2();
frm2.TakeThis(arrayOfInt);
frm2.Show();
In the form2 i created TakeThis(int[]) that catches the values from the form1 and display the values of the array on a label. Now, i cannot figure how to add some values to array. For example arrayOfInt[2] and arrayOfInt[3] and send to Form3.
Edit:
I decided to use a List to store my data but at the end I must convert a
list to an array because I am doing some reporting and math operations with the data.
This example is different from the example above. In this store all inputs from textboxs,comboxes in the list. At the end i need to convert the list into an array.
What have I done,
I created a new global class:
static class List{
static List<string> list;
public static void NewList(){
list=new List<string>();
}
public static void Save(string value){
list.Add(value);
}
public static void Display(){
foreach(var value in list){
MessageBox.Show(value);
}
}
}
The data is inserted between forms,
List.save(some_strings);
...
but at the end I need to convert the list in an array. I googled and I find the ToArray() function but i dont know how to use in my code. I tried with properties but i couldn't do the conversion. Please help.
Edit2
I found the solution.
In the global static class List I created a method that returns a List of strings:
public static List<string> GetList(){
return list;
}
Then, I created a new empty List of strings on Form2. Copied the old list to the new list and converted it in an array.
List<string> li=new List<string>();
li=List.GetList();
string[] temp=li.ToArray();
Don't use arrays if you want a data structure that you need to add items to.
Use a generic collection like List<T>.
In your case, a list of integers would be a List<int>.
IList<int> listOfInt = new List<int>();
listOfInt.Add(19);
listOfInt.Add(12);
Form2 frm2 = new Form2();
frm2.TakeThis(listOfInt);
frm2.Show();
When on Form2, your TakeThis function would look like this:
public voidTakeThis(IList<int> listOfInt)
{
listOfInt.Add(34);
}
This will also work when passing the list to another form, as List is a reference type whereas arrays are value types. If you don't know what this means, see this article.
Rather use ArrayList or even better IList<T>.
Arrays cannot be resized in C#
You will have to use ref argument on frm2.TakeThis() method:
Here is an MSDN article on it : Passing Arrays Using ref and out (C# Programming Guide).
void TakeThis(ref Int32[] array)
{
// Change array
}
and use like:
frm2.TakeThis(ref arrayOfInt);
Arrays need to passed by reference if you want to persist changes to them.
If you must not use an Array use a Collection like System.Collections.Generic.List<T>.
Use List<Int> and use oList.Add(item) method to add elements as array is Fixed in Lenght (you already giving it size at a time of initialization)
But if you want to use array at any cost then make a logic to create a new array upto the size of Old+ new added element and return that.
UPDATED
I believe you are facing problem because you have taken List of String instead or Int.
List<int> oIntList = new List<int>();
oIntList.Add(1);
oIntList.Add(3);
oIntList.Add(4);
oIntList.Add(5);
int[] oIntArr = oIntList.ToArray();

How can I transform or copy an array to a linked list?

I need to copy an array to a linked list OR transform the array in a linked list.
How this can be done in .NET (C# or VB)?
Thanks
Depending on what version we're taking about here, you can :
LinkedList<YourObjectType> ListOfObjects=new LinkedList<YourObjectType>(YourObjectArray);
To go to LinkedList from array:
var array = GetMyArray();
LinkedList<MyType> list = new LinkedList<MyType>(array);
To go to array from LinkedList:
var array = list.ToArray();
In .Net v2.0 or above:
Object[] myArray = new Object[] { 1, "Hello", 2, 3.0 };
LinkedList<Object> linkedList = new LinkedList<Object>(myArray);
You can replace Object with the type of element that the array actually holds.

Dynamic array in C#

Is there any method for creating a dynamic array in C#?
Take a look at Generic Lists.
Expanding on Chris and Migol`s answer with a code sample.
Using an array
Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");
Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.
List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)
In this case you may use the ToArray() method after initiating your List dynamically
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
string[] array = list.ToArray();
Of course, this has sense only if the size of the array is never known nor fixed ex-ante.
if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)
List<T> for strongly typed one, or ArrayList if you have .NET 1.1 or love to cast variables.
You can do this with dynamic objects:
var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };
foreach(var keyvalue in dynamicKeyValueArray)
{
Console.Log(keyvalue.Key);
Console.Log(keyvalue.Value);
}
Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array.
Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed
Dynamic Array Example:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
This answer seems to be the answer you are looking for Why can't I do this: dynamic x = new ExpandoObject { Foo = 12, Bar = "twelve" }
Read about the ExpandoObject here https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx
And the dynamic type here https://msdn.microsoft.com/en-GB/library/dd264736.aspx

Categories

Resources