Generic lists in array list - c#

There is a array list that contain generic lists. How can i access the variables that in generic list? But i want to access the variables via the array list.
ArrayList TheList = new ArrayList();
List<NewType>[] GenericLists = new List<NewType>[4];
GenericLists[0].Add(variable);
.
.
.
for (int i = 0; i < 4; i++)
{
TheList.Add(GenericLists[i]);
}
How can i print the variables via the Array list?

You need to iterate over the items of your ArrayList and cast each item to List<NewType> then you can iterate over the items in the lists and display them or whatever you want...
foreach(var list in TheList)
{
var currentList = (List<NewType>)list;
...
}
Or you can use Linq methods to cast them:
foreach(var list in TheList.Cast<NewList>())
These assumes that all items in the array list are of type NewList. Otherwise you will get an InvalidCastException at runtime. To avoid this you can use is or as operators to check if the type is NewList, or you can use OfType method which does this for you:
foreach(var list in TheList.OfType<NewList>())

Related

Collections in #c (ArrayList) in for loop or foreach with index

C# is new to me and I am trying to iterate through a collection, in this case I tried an ArrayList of one of my Classes, which I often used in Java. The goal is to loop and compare the ArrayList and get the index of the current position.
Why is it not possibel to initiate an ArrayList with a Type
ArrayList<MyClass> myAL = new ArrayList<MyClass>();
Why can't I typecast the ArrayList to get access to public methods of MyClass
ArrayList myAL = new ArrayList();
for (int i=0; i<myAL.Count; i++)
{
(MyClass)myAL[i].getSomeValue();
}
The only loop that works is the foreach loop, but I don't know how to access the index.
foreach (MyClass mc in myAL)
{
mc.getSomeValue();
//index??
}
Unlike Java, ArrayList in C# is not generic. If you want a type parameter, you should use List<T> from the System.Collections.Generic namespace. List<T> is actually preferred to ArrayList - the latter is still around mostly for backwards compatibility.
List<MyClass> myAL = new List<MyClass>();
You need an additional pair of parentheses for that:
ArrayList myAL = new ArrayList();
for (int i = 0; i < myAL.Count; i++)
{
((MyClass)myAL[i]).getSomeValue();
}
But there's no need for casting if you use List<T>.
You can't access an index directly in the foreach loop, but you can define a variable to hold it.
int index = 0;
foreach (MyClass mc in myAL)
{
// do stuff with the list item and an index
index++;
}
But I would recommed using a simple for-loop if you need to access an index directly.
foreach use Enumerator to loop over collection, index is not part of it, instead it uses MoveNext. MoveNext forces loop to move to next object
Assume list is like this
List<MyClass> list = new List<MyClass>();
and then get enumerator in list
var listEnumerator = list.GetEnumerator();
then use for loop to iterate over listEnumerator
for(var i = 0; listEnumerator.MoveNext() == true; i++ )
{
Console.WriteLine("Index: {0} and value is: {1}", i, listEnumerator.Current);
}
output
Index: 0 and value is: value1
Index: 1 and value is: value2

Difference between Add and AddRange in arrayList c#

Can anyone tell when to use Add() and AddRange() of ArrayList?
If you want to add a large number of values at one time, use AddRange.
If you are only adding a single value or adding values infrequently, use Add
Difference Between Add and AddRange
Add---------It is used to add the item into the list one by one.
AddRange-----------It is used to add the bulk of list item into the another list.
List<string>list1=new List<string>();//using Add
List<string>list2=new List<string>();//using AddRange
list1.Add("Malathi");
list1.Add("Sandhiya");
list1.Add("Ramya");
list1.Add("Mithra");
list1.Add("Dharshini");
list2.AddRange(list1);
output:
//The output of list1 contains
Malathi,
Sandhiya,
Ramya,
Mithra,
Dharshini
//The output of list2 Contains
Malathi,
Sandhiya,
Ramya,
Mithra,
Dharshini
C# List class represents a collection of a type in C#. List.Add(), List.AddRange(), List.Insert(), and List.InsertRange() methods are used to add and insert items to a List.
AddRange - AddRange adds an entire collection of elements. It can replace tedious foreach-loops that repeatedly call Add on List.
public virtual void AddRange (System.Collections.ICollection c);
Add - Add method adds an object to the end of the List.
public virtual int Add (object value);
Example: Now set an array of elements to be added to the list.
// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;
Use the AddRange() method add the entire collection of elements in the list −
List<int> list = new List<int>();
list.AddRange(arr);
But if you want to use List.Add() method,
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
For details, you can check Insert an Item into a C# List
If You want to add single variable in List, then Add() is used.
But if you want to add List or multiple variable in List, then AddRange() can be used
var t = (from t1 intable1
join t2 in table2 on t1.t1id equals t2.t2id
select new ABCViewModel
{
FirstName = t1.firstname,
LastName = t1.Lastname
})
.where(t2.age>35)
.ToList();
var s = (from t1 intable1
join t2 in table2 on t1.t1id equals t2.t2id
select new ABCViewModel
{
FirstName = t1.firstname,
LastName = t1.Lastname
})
.where(t2.age < 35)
.ToList();
t.AddRange(s);
return t;
It will add result of List s to List t along with result of List t.
Difference b/w Add() and AddRange() methods is very straight forward
Add() is used to add an element in the list.
AddRange() is used to add a range of elements(multiple elements) at once in the list.
Note: Multiple elements can be another entire Array, HashTable, SortedList, ArrayList, BitArray, Queue, and Stack.
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//create the first arraylist
ArrayList arraylist1 = new ArrayList();
arraylist1.Add(5);
arraylist1.Add(7);
//create the second arraylist
ArrayList arraylist2 = new ArrayList();
arraylist2.Add("Five");//add the single value at time to the arraylist
arraylist2.Add("Seven");//add the single value at time to the arraylist
//perform AddRange method
arraylist1.AddRange(arraylist2);//adding the arraylist as bulk in another arraylist
// Display the values.
foreach (object i in arraylist1)//iterating the arraylist1 value to object
{
Console.WriteLine(i);
}
}
}
}

How create many list as array?

I have a problem on creating a set of list in array
this is my coding but it's wrong one, any correction for this?
List<string>[] item = new List<string>[10]();
I want to create 10 list in string named as item but I can't do it
and then how can I store more than 1 element in each of the 10 item list??
item[1].add(a); //when I want to print that a I use item[1][0]
item[1].add(b); //when I want to print that b I use item[1][1]
item[2].add(aa);
item[2].add(bb);
but how can I store element in each of the list?
If you KNOW for certain that you want exactly ten lists, you can use an array instantiated to 10 items, each a list of string.
List<string> [] items = new List<string> [10];
Each List is not initialized, so you need to initialize your list before you can use it and each list can be accessed via normal indexer syntax..
if (items[0] == null)
items[0] = new List<string>();
Once initialized, you can fill in your data.
items[0].Add("another string");
If you wanted to pre-initialize each list so that you do not get a NullReferenceException, do so in a loop.
for (var i = 0; i < items.Length; i++)
items[i] = new List<string>();
However, if you think that your items may need to hold more List<string> down the road, just simply use a list of lists.
List<List<string>> items = new List<List<string>>();
List wraps array and gives you some nice syntactic sugar and optimizations for expanding arrays which makes your life a lot easier. You can still use indexer syntax to access each list within your list.
if (items[0] == null)
items[0] = new List<string>();
items[0].Add("another string").
As per your comments
"I want 10 separete list that have dynamic space"
You can define your collection as follows.
List<string> [] collection= new List<string> [10];
for(int i=0; i<10; i++)
collection[i] = new List<string>();
or, if you don't care size of the array then you can use this.
List<List<string>> collection = new List<List<string>>();

Adding elements from a ListBox to a List

I have a ListBox with Integers in it that gets them from a SQL database. Now I wanted to put these elements into a List when they get selected but somehow it won't work. Here is the code:
List<Int32>typeElements = new List<Int32>();
if(form1.listBox.SelectedIndex != -1)
{
foreach (var selectedItem in form1.listBox.SelectedItems)
{
typeElements.Add(selectedItem);
}
}
He tells me he can't convert object to int and that the method has some invalid arguments. How to handle that?
ListBox.SelectedItems is a collection of objects. You can't simply take an element from this collection and add it to a typed list of integers.
You need a conversion
typeElements.Add(Convert.ToInt32(selectedItem));
If you want to use Linq and the IEnumerable extensions then you could write your loop in one line
// List<Int32>typeElements = new List<Int32>();
List<Int32> typeElements = form1.listBox.Items.Cast<int>().ToList();
EDIT:
Following your comment then you need to extract the Integer element from the DataRowView
DataRow row = (selectedItem as DataRowView).Row;
typeElements.Add(row.Field<int>("NameOfYourDataBaseIntegerField"));
Try this (using System.Linq):
OfType() is an extension method, so you need to use System.Linq
List<Int32> selectedFields = new List<Int32>();
selectedFields.AddRange(listbox.CheckedItems.OfType<Int32>());
Or just do it in one line:
List<Int32> selectedFields = listbox.CheckedItems.OfType<Int32>().ToList();

how to get count ArrayList in dictionary wpf c#

I want to get count of list but my list is in dictionary.
Dictionary < string, ArrayList > ();
wording["utterance"+x].Count; // this gives me count for items in dictionary.
What I want to know is:
how many items I are there in my ArrayList?
how to refer to the elements in the list?
You could of course do:
ArrayList al = wording["key"];
int count = al.Count;
I'm curious why your initial code wouldn't work though, unless Linq extensions are interfering.
I would go with Amicable's suggestion of List<T> over ArrayList though.
how many items I are there in my ArrayList?
(wording["utterance"+x] as ArrayList).Count; // gives count of items in ArrayList
how to refer to the elements in the list?
wording["Actual Key"][<numeric index of item number>; // wording["utterance"+x][0] in your case for first item in arraylist
how many items I are there in my ArrayList?
The code you gave should do just that:
// number of items in the ArrayList at key "utterance" + x
wording["utterance"+x].Count;
how to refer to the elements in the list?
You can refer to them by index:
// get the 4th item in the list at key "key"
object myObject = wording["key"][3];
Or you can iterate over them:
foreach (object item in wording["key"])
DoSomething(item);
To summarize, wording is a Dictionary that stores ArrayLists by a string key. You can retrieve a particular ArrayList by indexing with the appropriate string key for that ArrayList.
wording // evaluates to Dictionary<string, ArrayList>
wording["sometext"] // evaluates to ArrayList
Note that the latter will throw an exception if you have not already placed an ArrayList at that key.

Categories

Resources