Create an object out of an array - c#

Perhaps I didn't explaine myself the first time around so here is my second go at it.
I need to declare objects from a list of strings inside an array.
So my array goes out to a DB and collects the names from one colums. This names will all be an object. Now I want to define each object with that name fromt he column dynamicly.
So the array has say 5 elements in it of type string.
So going though my for look i cannot seem t o dynamicly create the object.
So instead of manually going myobject test = new myobject();
I just want to declare it by looping though the array.

I'am not pretty sure what your question is, but if I see your code than you want to create objects in your array?
Maybe this is your solution:
MyObject[] myArray = new MyObject[4];
for (int i =0; i < myArray.Length; ++)
{
myArray[i] = new MyObject();
}
Hope this will help you.

MyObject[] myArray = new MyObject[3];
for (int i =0; i < myArray.Length; i++)
{
MyObject obj = new MyObject();
myArray[i] = obj;
}

You can convert an array to objects by using System.Linq's select operator. You create an object for every i in the array and return a new object for it like this
var array = new string[2]{"one","two"};
var objects = array.Select(i=> new Object{Name = array[i]}).ToArray();

Related

Retrieving datas from an ArrayList filled with another ArrayList

I got 2 ArrayList objects on my project defined as
ArrayList final_list = new ArrayList();
ArrayList temp_list = new ArrayList();
I needed to fill my final_list with the other one, so I used a loop using final_list.Add(temp_list) inside of it, which works fine.
Here is an exemple about what my final_listobject looks like after the loop :
The fact is I need to process the datas after the loop. So I guess I'll have to do something like
for (int i = 0; i < final_list.Count; i++)
{
for (int j = 0; j < 6 ; j++)
{
// Retrieving my [0,0] , [0,1], ... , [final_list.Count,5] datas
}
}
but this isn't working.
Anyway, I'm even struggling on the correct syntax to use so I already tried hard coded things like final_list[0,1] or final_list[0][1]to display the 10 value for exemple, but it doesn't work.
How can I manage to do that ?
Seems you have a collection (final_list), which contains some collections inside. And now you want to process the inner most elements.
First of all, you'd better use generic collections instead of old ArrayList.
Generally, handling such a scenario can be done like this:
foreach( List<string> innerList in final_list)
{
foreach( var innerMostItem in innerList)
{
// process the element!
}
}
or equivelantely:
foreach( var innerList in final_list)
{
foreach( var innerMostItem in innerList as List<string>)
{
// process the element!
}
}
By the way, naming convention of C#, is to use camelCase for variables.
update
code snippet above is updated. Not the type casting in the inner loop!
Though innerList was originally an IEnumerable, it is retrieved from the final_list as an instance of object class. You need to explicitly cast it to ArrayList or you will get an exception.

Copy 2d array of list

I have a list List<MyClass>[,] myarraylist; and it is filled.
I want to copy it to List<MyClass>[,] mycopy then change mycopy without changing myarraylist.
What is the quickest way of doing this?
It kind of depends on what you really want to do. You can easily clone the array:
List<MyClass> mcopy = new List<MyClass>[marraylist.GetUpperBound(0)+1,marraylist.GetUpperBound(1)+1];
for (int i = 0; i < marraylist.GetUpperBound(0); ++i)
{
for (int j = 0; j < marraylist.GetUpperBound(1); ++j)
{
mcopy[i,j] = marraylist[i,j];
}
}
Now, that gives you a copy of the array. But, mcopy[1,2] has a reference to the same list as does marraylist[1,2]. If you modify that list, that is if you were to write:
mcopy[1,2].Add(new MyClass(...));
Then that would also modify the list that is referenced in marraylist[1,2].
If you want to create copies of the lists, then the code in your inner loop has to be:
mcopy[i,j] = new List<MyClass>(marraylist[i,j]);
That creates a new list, so if you modify the list at mcopy[1,2], you don't modify the list in the original array.
But that might not be what you want, either. Because although mcopy[1,2] contains a different list than marraylist[1,2], the lists have the same contents. So if you wrote mcopy[1,2][1].SomeProperty = 42;, then you'll also modify the contents of the object at marraylist[1,2][1], because they're the same object.
If you want to copies of the lists and copies of the objects, then your inner loop code becomes:
mcopy[i,j] = marraylist[i,j].Select(m => new MyClass(/* create from m */)).ToList();
The /* create from m */ comment means that you either pass m to the copy constructor (if you have one), or pass the individual parameters, or if you have a clone method on the class you'll use that. Somehow you want to make a deep copy of the MyClass instance.
Yes, it's complicated. The word "copy" is quite overloaded here, and how you proceed depends entirely on what definition of "copy" you're using. Do you want to make a copy of the array (just copy the references), the array's contents (create new lists with the same objects), or the lists' contents (create new lists with new objects that contain the same data)?
If MyClass has a copy constructor:
var newList = new List<MyClass>[oldList.GetLength(0), oldList.GetLength(1)];
for (int i = 0; i < oldList.GetLength(0); i++)
for (int j = 0; j < oldList.GetLength(1); j++)
newList[i, j] = oldList[i, j].Select(x => new MyClass(x)).ToList();
If it doesn't have a copy constructor, and you can't add one, you will have to write your own function to make a copy of MyClass.
newList[i, j] = oldList[i, j].Select(x => CloneMyClass(x)).ToList();
This may work. It is an extension method to 2D IEnumerables. That means it can be used with anything that implements the IEnumerable interface, as long as your class T implements ICloneable.
public static IEnumerable<IEnumerable<T>> Clone<T>(this IEnumerable<IEnumerable<T>> twoDList) where T : ICloneable
{
if (twoDList != null)
{
List<List<T>> result = new List<List<T>>();
for (int i = 0; i < twoDList.Count(); i++)
{
List<T> aList = new List<T>();
for (int j = 0; j < twoDList.ElementAt(i).Count(); j++)
{
aList.Add(twoDList.ElementAt(i).ElementAt(j));
}
result.Add(aList);
}
return result;
}
else
{
return null;
}
}
It should also work with jagged 2D structures that implement IEnumerable.
Example Usage follows:
List<List<MyClass>> cloned = original2DStructure.Clone();
Help on making your class implement ICloneable could be found here.

Can I put multiple datatypes in an array?

In Lua and Javascript you can put different datatypes in an array. Bools; Strings; Ints and such. But I see that in C#, the arrays look something like
string[] keysPressed ={};
So... Can I not put different datatypes in an array? Yes I know its obvious that you cant in that line. But is there like some other way I can create an array that supports different things?
You are looking for an array or collection of dynamic.
For more MSDN Dynamic data type
Dynamic can be used as we do in lua and JS. These are dynamically typed languages.
dynamic d1 = 7;
dynamic d2 = "a string";
dynamic d3 = System.DateTime.Today;
dynamic d4 = System.Diagnostics.Process.GetProcesses();
Here is an example of using them in array
dynamic[] myObjects = new dynamic[3];
myObjects[0] = 1;
myObjects[1] = "2";
myObjects[3] = "another string";
You can also use an object array.
object[] keysPressed ={};
You can use object[] or any other collection of objects:
List<object> objs = new List<object>();
objs.Add(1);
objs.Add("Str");
objs.Add(DateTime.Now);
Remember that every item in this collection is an object, and you will need to cast them in order to use:
objs[1].Trim() // won't compile. object has no Trim method
((string)objs[1]).Trim() // OK
((string)objs[0]).Trim() // runtime exception, unable to cast
Another important thing that you need to keep in mind is that adding primitives to this collection results in boxing.
object array, however,it need to be remember which type you
store and cast it to the right type when you use the element. It's possible to throw an
Exception in run time.
Tuple
generic collection
Why you don't use dynamic feature.
List<dynamic> dynamicList = new List<dynamic>();
string stringValue = "Akshay";
int intValue = 1;
dynamicList.Add(stringValue);
dynamicList.Add(intValue);
You can either use the collection
ArrayList array = new ArrayList();
string stringValue = "Akshay";
int intValue = 1;
array.Add(stringValue);
array.Add(intValue);

Is it possible to instantiate objects with variable names, or access variable names at runtime?

I have quite a few lines of code that create objects and using various parameters with similar object names and constructors. The only thing that is changing is the actual name of the object variable being created, and the name of the objects themselves being passed in. Here is an example of code that matches my current setup:
BackyardObject backyardObject0 = new BackyardObject(cat0, dog0, goat0, piglet0);
BackyardObject backyardObject1 = new BackyardObject(cat1, dog1, goat1, piglet1);
BackyardObject backyardObject2 = new BackyardObject(cat2, dog2, goat2, piglet2);
BackyardObject backyardObject3 = new BackyardObject(cat3, dog3, goat3, piglet3);
BackyardObject backyardObject4 = new BackyardObject(cat4, dog4, goat4, piglet4);
// many many more BackyardObjects being instantiated
As we can see, the names of the object being created match exactly the names of the objects being passed into the constructor. Is it possible to create a loop that would set all this up?
Edit
I think I might have lacked details that were needed to get a correct answer for this question. It isn't a question on "how-to" use a loop, or how to add items to a collection it's more of a question to determine if is it possible to create a "variable name" dynamically inside of a loop, while accessing another variable name dynamically inside of the loop provided the information given above (just made up code on the spot).
// psuedo code for something I'm asking is possible
for( i = 0; i < 10; i++)
{
// create BackyardObject with generic name, while appending "i" to
// variable name, and accessing other object variables
BackyardObject backyardObject'i'
= new backyardObject(cat'i', dog'i', goat'i', piglet'i');
}
While I understand that I could create additional arrays and lists to store objects and then use those, I was just seeing if it was possible to get variable names dynamically. I wasn't sure if it was entirely possible, that's why I asked the question. I know that this is a strange question, but got curious after I seen this Objective-C code:
// Getting an arrayName dynamically based on loop index
for (int i = 0; i < 10; i++)
{
NSString *arrayName = [[NSString alloc] initWithFormat:#"column%d",
i];
NSArray *array = [self valueForKey:arrayName];
}
Objects don't have names... what you're talking about is variables. And rather than having lots of variables with numbers as suffixes, you'd be better using collections - arrays, or lists, or whatever. Then you can do:
// Or use arrays...
List<Cat> cats = new List<Cat>();
cats.Add(new Cat(...)); // Add the cats however you want to set them up
// Ditto dogs, goats etc
List<BackyardObject> backyardObjects = new List<BackyardObject>();
for (int i = 0; i < 10; i++)
{
backyardObjects.Add(new BackyardObject(cats[i], dogs[i],
goats[i], piglets[i]));
}
I assume you're fairly new to C# - I suggest you look at arrays and collections in whatever you're learning from.

how to make array of class objects using dynamic allocation in c#?

i made a class named x;
so i want to make array of it using dynamic allocation
x [] myobjects = new x();
but it gives me that error
Cannot implicitly convert type 'ObjAssig4.x' to 'ObjAssig4.x[]'
i know it's dump question but i am a beginner
thanks
x[] myobjects = new x[10];
For an array you don't create a new one with parens 'new x()'
An array is not dynamic though.
You could use Array.Resize to alter it's size, but you're probably after a List
List<x> myobjects = new List<x>();
myobjects.add(new x());
You don't want to use an array but a list
List<SomeObject> myObjects = new List<SomeObject>();
FYI you were declaring the array wrong too.
It should be
x[] myobjects = new x[5];
x [] myobjects = new x[numberOfElements];
Creates an array of numberOfElements references to objects of type x. Initially those references are null. You have to create the objects x independently and store references to them in Your array.
You can create an array and some objects whose references will end up in the array, using an initialisation list like:
x [] myobjects = new x[3] {new x(), new x(), new x()};
i Found that i can do this
x [] myobjects = new x[]{
new myobjects{//prop. goes here},
new myobjects{//prop. goes here}
}
The error
Cannot implicitly convert type
'ObjAssig4.x' to 'ObjAssig4.x[]'
is telling you that you are trying to declare a new x and assign it to your array. Instead, you need to declare a new array (which will also need a size):
x[] myobjects = new x[100];

Categories