Create ArrayList in one step - c#

I'm desperately trying to create an ArrayList out of objects of an enumeration in one step in C# with Visual Studio 2012.
It should look like something of the following:
new ArrayList( {class1.enum.sample1, class1.enum.sample2, class1.enum.sample3} );
When I'm writing it in two lines, it works:
class1.enum[] array = {class1.enum.sample1, class1.enum.sample2, class1.enum.sample3};
ArrayList test = new ArrayList(ha);
But I need to write it in one line. Could you help me, please?

You need another collection like an array to be able to use the collection initializer:
var al = new ArrayList { new[] { class1.enum.sample1, class1.enum.sample2, class1.enum.sample3 } };
But there is no reason to use the old ArrayList anymore. In this case you could use a List<class1.enum> (apart from the fact that enum is a keyword).

You do not need parenthesis () for array list initializer. You can initialize in a single line as under.
ArrayList test = new ArrayList{class1.enum.sample1, class1.enum.sample2, class1.enum.sample3}
Array list should be replace with generic list unless you have solid reason to use Arraylist. You can find more about using generic list in Benefits of Generics on MSDN

Related

Does ArrayList in C# can contain objects various types?

Is it possible, to do something like that:
ArrayList arl = new ArrayList();
arl.Add(1);
arl.Add("test");
int[,] tab = new int[4, 4];
init(tab);
arl.Add(tab);
Is it possible to contain objects of various types (Like in JavaScript or Lua)? (C#)
Yes, ArrayList contains elements of type object so this means you can put everything in it. When retrieving it again, you can then case it back to its original type.
Of course, due to this casting it's less efficient.
Yes it is possible. ArrayList stores a collection of the type object meaning you can insert any .NET type.
You should really use List<T>. For example:
List<int> listIntegers = new List<int>();
listIntegers.Add(1);
You could also use List<object> however you will have to unbox all of the items in the list. Which potentially may incur performance issues.
You can have diffent types in a ArrayList
try this:
var ary = new ArrayList();
ary.Add("some string");
ary.Add(23.4);
ary.Add(new StringBuilder());
ary.Add("some other string");
You can then query it like this:
string[] strings = ary.OfType<string>();
StringBuilder[] stringBuilders = ary.OfType<StringBuilder>();
As for your question, yes ArrayList can contain various object types. It is generally recommended by Microsoft to use List<T> instead, to prevent the need of boxing and unboxing to Type object when using the same types.
If you have a recurring pattern of types it might be more helpful (and faster) to define a custom class:
protected class arl_items
{
public string item1 {get; set;};
public int item2 {get; set;};
public int[4,4] item3 {get; set;};
}
and then go:
List<arl_items> arl = new List<arl_items>();
But if there is no pattern to your value-types you can as well use ArrayList, because creating List<object> would be meaningless, as they are the same.
Just btw. i prefer using List<object> over ArrayList, but that is only my personal preference
Yes it can since it does not do any type checking, it can sometimes be faster than a List<T> when working with reference types, though it is generally not recommended to use it when you have a perfectly fine type safe alternative.
Any type that inherits from object can be stored in an ArrayList. Whenever you access an item in an ArrayList you must be careful to cast it to the correct type or else you will get a compiler error.
I believe ArrayList is an old relic from the days before generic types in .Net

Convert IEnumerable to List<string> in .net 2.0

I need to convert IEnumerable to a List<string>. one of the way is to itearte through this and add each object to a list but this process is vary time consuming. Is there any other way to do this. Any help would be appreciated.
You can pass the enumerable directly into the constructor of a new List<string> instace:
List<string> list = new List<string>(yourEnumerable);
or you can use the AddRange method:
List<string> list = new List<string>();
list.AddRange(yourEnumerable);
This answer assumes that you in fact already have an IEnumerable<string>.
If this is not the case, your only option is a loop:
List<string> list = new List<string>();
foreach(object item in yourEnumerable)
list.Add(item.ToString());
BTW: You are saying:
one of the way is to itearte through this and add each object to a list but this process is vary time consuming
You need to iterate the enumerable in any case. How else would you get all values? In the first two sample codes I gave you, the enumeration is performed inside the List<T> class, but it is still happening.

Add a List<object> or Arraylist to an array of CustomObject[]

I have tried many ways like
Cast<CustomObject>, as Customobject and ToArray(Customobject) but nothing worked.
How can I add List or ArrayList via AddRange to a CustomObject[] Array?
Code is really difficult.
But if you have some time you can get the complete source of the destination list from here:
http://www.codeproject.com/Articles/4012/C-List-View-v1-3?msg=3844172#xx3844172xx
This is a Custom Listview
I activated a combobox for the second column, so I can select diferrent values for a cell.
But before this, I have to add something to select.
This is the hole problem.
Update:
Firstly, thanks for the help !
Secondly, Found a solution in the comments from the website with the source.
Had to add some code and changed the destination custom array to a List
list.Cast<CustomObject>().ToArray()
Will work as long as the things in the list are actually CustomObject. If they might be other types, you can use OfType<CustomObject>() instead of Cast. This will filter out anything of an incompatible type.
Assuming the objects really are instances of CustomObject, use LINQ Select method:
objList.Select(o => o as CustomObject).ToArray();
Otherwise you will get an array of null.
If its a List<CustomObject> then let us say
CustomObject[] coarr = list_of_customobject.ToArray();
If its an ArrayList then
CustomObject[] coarr = arraylist.OfType<CustomObject>().ToArray();
If you are unsure whether all of your objects are of the type CustomObject try
var result = list.OfType<CustomObject>.ToArray();
Strictly speaking you cannot add elements to an array, since an array's length remains constant over its lifetime. There are two things you can do:
Create a new array
myArray = myTList.ToArray() // generic)
myArray = myArrayList.Cast<CustomObject>().ToArray() // cast, non-generic
myArray = myArrayList.OfType<CustomObject>().ToArray() // filter by type, non-generic
Set elements of an array
myArray[x] = myTList[y] // generic
myArray[x] = (CustomObject)myArrayList[y] // non-generic
I recommend you to take the generic collection whenever possible. They provide you additional type safety. Casting object variables cause runtime errors you could detect at compile time by using generic types.
If you actually want to add elements to an existing collection, you may try to use a dynamic collection type rather than an array: List<T> : IList<T> or LinkedList<T> : ICollection<T> are a good point to start, or maybe more specific types like Stack<T> or Queue<T>.

How can I create a sequence of numbered variables at run time?

Friends, I must create a series of ArrayLists, each containing objects of unknown origin, with each instance assigned to a separate local variable.
So far, so good... But I also need each local variable's name to follow a very specific pattern: the name should begin with "oArr", followed by one or more digits reflecting that particular array's position within the sequence. Furthermore, I will not know at compile-time how many of these arrays - and hence, how many local variables - I will be needing!
It strikes me that this is perhaps a problem that could be solved by the availability of dynamic types in C# 4.0, however I am not at all familiar with their use. How might I take code like this...
int i=0;
foreach(something)
{
ArrayList oArr+i=new ArrayList();
i++;
}
...and turn it into something that matches the criteria outlined above and actually compiles?
Alternately, is there a more simple, sane approach to this problem?
You cannot change the name of a variable during execution, since the code (even c# code) was compiled with a certain variable name. If you could change the name during execution then it would cause problems.
For example, if the language allowed to change variable names then when you try to access a variable named 'var1' the compiler has no idea if during execution that variable name changed and now is called 'x'.
Something you could try to do is to allow your program to dynamically compile some code but this is probably not the right solution to your problem. If you explain better what you need then we could provide you with an effective solution.
Hope this helped
EDIT: Seeing your editions I can tell you that it is impossible with the approach you are currently using. I could suggest you the following:
int i = 0;
List<ArrayList> masterList = new List<ArrayList>();
foreach (something)
{
masterList.Add(new ArrayList());
i++;
}
If what you need is to have each ArrayList to have a specific name you can recall you can use a dictionary:
int i = 0;
Dictionary<string, ArrayList> masterList = new Dictionary<string, ArrayList>();
foreach (something)
{
masterList.Add("oArr" + i.ToString(), new ArrayList());
i++;
}
ArrayList al = masterList["oArr1"];
Would this work for you?
var arrayLists = new List<ArrayList>();
var i = 0;
foreach(var item in list)
{
arrayLists.Add(new ArrayList());
i++;
}
Then you can access each array list by index.
Use a List of ArrayLists.

string.split returns a string[] I want a List<string> is there a one liner to convert an array to a list?

Lists in C# have the .ToArray() method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.
I am using the String.Split method in the .NET 2.0 environment, so LINQ, etc. is not available to me.
string s = ...
new List<string>(s.Split(....));
In .Net 3.5, the System.Linq namespace includes an extension method called ToList<>().
return new List<string>(stringArray);
If all you need is an object that implements the IList interface and you do not need to add new items you might also do it like this:
IList<string> list = myString.Split(' ');

Categories