I have to declare a list and use it in my code.How ever the number of elements that i will add to list will vary during each time I run my code.So how can I create a list and add elements to it dynamically with out specifying its size during declaration?
var myList = new List<string>();
myList.Add("foo");
myList.Add("blah");
// and on and on ...
List's in .Net will automatically resize themselves as you add to them.
You don't have to specify the bounds of a list (as you do with arrays). You can keep on calling Add() method to add elements in the list. You can create either a generic list which takes only specified types of objects and a non-generic list that only takes objects:
Generic:
List<int> intList = new List<int>();
intList.Add(10);
intList.Add(20);
Non-Generic:
ArrayList objList = new ArrayList();
objList.Add(New Employee());
objList.Add(20);
objList.Add("string");
The later can take any type of object but is not type-safe.
The System.Collection namespace is full of collection classes that can dynamically contract and expand its size, see the Generic namespace for the most used classes: http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
I recommend sticking with a List if you doubt what you are doing:
var list = new List<string>();
list.Add("test1");
list.Add("test2");
list.Remove("test1");
Related
I am trying to do
var mahByteArray = new ArrayList<byte>();
And it does not work.
It says this:
The non-generic type 'System.Collectios.ArrayList' cannot be used with
type arguments
What is the proper way to do declare a byte ArrayList?
You are confusing Java ArrayList collections with C# List generic collections. Both are used to declare collections, but the first one is used in Java as being a type defined in the generic class List for Collections framework and in the last one is used in C# language as an implicit generic type.
So, you must declare as being a List type. See details on List.
var mahByteArray = new List<byte>();
or
List<byte> mahByteArray = new List<byte>() { 2, 3, 4 };
sure you can use a ArrayList
var mahByteArray = new ArrayList();
mahByteArray.Add((byte) 230);
ArrayList<> isn't generic. You can use generic List<> instead
var mahByteArray = new List<byte>();
ArrayList is not generic. Use System.Collections.Generic.List<T> instead. The List<T> class is the generic equivalent of the ArrayList class. It implements the IList<T> generic interface using an array whose size is dynamically increased as required.
var mahByteArray = new List<byte>();
Also take a look at this: Difference between ArrayList and Generic List.
I have an IEnumerable object as:
IEnumerable<string> listSelectedItems;
Which contains three items. Now i created a new object and want to get all items from listSelectedItems, so i wrote this code:
IEnumerable<string> newList = listSelectedItems;
But now when i alter newList, the listSelectedItems also gets altered. How can i achieve altering or creating a new IEnumerable without refernce.
Are you looking for this?
IEnumerable<string> newList = listSelectedItems.ToList();
IEnumerable is an interface, so you can't instantiate it, you need an implementation of it, for example List
IEnumerable<string> newList = new List<string>(listSelectedItems);
In your case setting newList = listSelectedItems means that newList will be just a reference to the listSelectedItems so if the underlying object is changed, newList will reference the changed object.
I'm working on one of the project Euler problems, and I wanted to take the approach of creating a list of values, and adding the list to a Hashset, this way I could evaluate in constant time if the list already exists in the hashset, with the end goal to count the number of lists in the hashset for my end result.
The problem I'm having is when I create a list in this manner.
HashSet<List<int>> finalList = new HashSet<List<int>>();
List<int> candidate = new List<int>();
candidate.Add(5);
finalList.Add(candidate);
if (finalList.Contains(candidate) == false) finalList.Add(candidate);
candidate.Clear();
//try next value
Obviously the finalList[0] item is cleared when I clear the candidate and is not giving me the desired result. Is it possible to have a hashset of lists(of integers) like this? How would I ensure a new list is instantiated each time and added as a new item to the hashset, perhaps say in a for loop testing many values and possible list combinations?
Why don't you use a value which is unique for each list as a key or identifier? You could create a HashSet for your keys which will unlock your lists.
You can use a Dictionary instead. The only thing is you have to test to see if the Dictionary already has the list. This is easy to do, by creating a simple class that supports this need.
class TheSimpleListManager
{
private Dictionary<String, List<Int32>> Lists = new Dictionary<String, List<Int32>>();
public void AddList(String key, List<Int32> list)
{
if(!Lists.ContainsKey(key))
{
Lists.Add(key, list);
}
else
{
// list already exists....
}
}
}
This is just a quick sample of an approach.
To fix your clear issue: Since its an object reference, you would have to create a new List and add it to the HashSet.
You can create the new List by passing the old one into its constructor.
HashSet<List<int>> finalList = new HashSet<List<int>>();
List<int> candidate = new List<int>();
candidate.Add(5);
var newList = new List<int>(candidate);
finalList.Add(newList);
if (finalList.Contains(newList) == false) //Not required for HashSet
finalList.Add(newList);
candidate.Clear();
NOTE: HashSet internally does a contains before adding items. In otherwords, here even if you execute finalList.Add(newList); n times, it would add newList only once. Therefore it is not necessary to do a contains check.
I am trying to figure out something. I have a method which adds some items into a ComboBox named "cbSize". I realize that if I add two types of data into it, the code will crash. Is this because a ComboBox can only accommodate one type of data?
items.Add(1);
items.Add(10);
items.Add(100);
items.Add(2);
items.Add(20);
items.Add(3);
items.Add(30); //works fine if add numbers only
//items.Add("4"); //will crash if mix both numbers and text
//items.Add("2"); //works fine if add text only
//then sort them out
items.Sort();
//now clear original cbSize items
cbSize.Items.Clear();
//and add them back in sorted order
cbSize.Items.AddRange(items.ToArray());
//gotta clear ArrayList for the next time or else things will add up
items.Clear();
Is this because a ComboBox can only accommodate one type of data?
No, try below it will work
cbSize.Items.Add("44");
cbSize.Items.Add(44);
problem is with your items collection, it is type safe. you can't add different types to it.
try with list of objects. it will work. reason is both int and string are objects
List<object> items = new List<object>();
items.Add(1);
items.Add(30);
items.Add("4");
items.Add("2");
//since you have string and int value you need to create custom comparer
items.Sort((x, y) => Convert.ToInt32(x).CompareTo(Convert.ToInt32(y)));
//now clear original cbSize items
cbSize.Items.Clear();
//and add them back in sorted order
cbSize.Items.AddRange(items.ToArray());
OR you can use ArrayList class (not type-safe because it can store any object)
var integers = new ArrayList();
integers.Add(1);
integers.Add(2);
integers.Add("3");
comboBox1.Items.AddRange(integers.ToArray());
What is type-safe in .net?
Yes. What you can do is to provide a Size class that will adapt from ints and strings:
items.Add(new Size(3));
items.Add(new Size(4));
items.Add(new Size("large"));
Then, you could make the Size class implement IComparable so you can call the Sort() method.
How would be a c# .net generic list in java?
somthing like that:
public class ClientList : List<Client> { }
the answer from Nikil was perfect, I just want to add to whoever wants to create a class from the List:
public class ClientList extends ArrayList<Client>
Java's List interface (java.util.List) can be generified. In other words, instances of List can be given a type, so only instances of that type can be inserted and read from that List. Here is an example:
List<String> list = new ArrayList<String>();
This list is now targeted at only String instances, meaning only String instances can be put into this list. If you try to put something else into this List, the compiler will complain.
The generic type checks only exists at compile time. At runtime it is possible to tweak your code so that a String List has other objects that String's inserted. This is a bad idea, though.
Accessing a Generic List
You can get and insert the elements of a generic List like this:
List<String> list = new ArrayList<String>();
String string1 = "a string";
list.add(string1);
String string2 = list.get(0);
Notice how it is not necessary to cast the object obtained from the List.get() method call, as is normally necessary. The compiler knows that this List can only contain String instances, so casts are not necessary.
Iterating a Generic List
You can iterate a generic List using an iterator, like this:
List<String> list = new ArrayList<String>();
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String aString = iterator.next();
}
Notice how it is not necessary to cast the object returned from the iterator.next() next call. Because the List is generified (has a type), the compiler knows that it contains String instances. Therefore it is not necessary to cast the objects obtained from it, even if it comes from its Iterator.
You can also use the new for-loop, like this:
List<String> list = new ArrayList<String>();
for(String aString : list) {
System.out.println(aString);
}
Notice how a String variable is declared inside the parantheses of the for-loop. For each iteration (each element in the List) this variable contains the current element (current String).