C# .NET and direct object collections - c#

Hey all is there a collection type like arrayList which i can add an object to using an ID?
effectively as the title of my post sugests a Direct object collection. so for example:
DirectCollection.addAt(23, someobject);
and
DirectCollection.getAt(23);
etc etc
i know arraylist is usable in that case but i have to generate the initial entry with a null reference object and if if the object has an ID like 23 i have to generate 22 other entries just to add it which is clearly impractical.
basically using the object position value as a unique ID.
Any thoughts?
Many thanks.

You could use Dictionary<int, YourType>
Like this:
var p = new Dictionary<int, YourType>();
p.Add(23, your_object);
YourType object_you_just_added = p[23];

Use a dictionary.
Dictionary<int, YourType>
It allows you to add/get/remove items with a given key and non continuous ranges.

You could use a Dictionary
The code for your example would be very simple:
Dictionary<int, AType> directCollection = new Dictionary<int, AType>();
directCollection.Add(23, someObjectOfAType);
AType anObject = directCollection[23];

I think KeyedCollection or Dictionary is what you need.

Use System.Collections.Hashtable. It allow to store the heterogeneous type of object (a Hashtable can hold the multiple type of object).
Example:
System.Collections.Hashtable keyObjectMap = new System.Collections.Hashtable();
//Add into Hashtable
keyObjectMap["Key_1"] = "First String";
keyObjectMap["Key_2"] = "Second String";
//Add the value type
keyObjectMap["Key_3"] = 1;
keyObjectMap["Key_4"] = new object();
//Get value/object from Hashtable
string value = (string)keyObjectMap["Key_2"];
int intValue = (int)keyObjectMap["Key_3"];

Related

C# - How can I correct string case in HashSet<string> within a Dictionary

I have a variable like below:
var dict = new Dictionary<string, HashSet<string>>();
I want to make sure the values in the HashSet are unique using StringComparer.Ordinal. What would be the syntax for that? Thanks.
Everytime you initialize a new key, the value should be passed an explicit parameter like this:
dict["some key"] = new HashSet<string>(StringComparer.Ordinal);

Do multidimensional arrays have to be of the same type? [duplicate]

I want to create two dimension array of different type like I can add to that array two values one of them is controlname and second is boolean value.
You can't do that. Instead, you should create a class that contains these two properties, then you can create an array of that type:
public class MyClass
{
public string ControlName {get;set;}
public bool MyBooleanValue {get;set;}
}
public MyClass[] myValues=new MyClass[numberOfItems];
Or, as Anders says, use a dictionary if one of the properties is meant to be used to perform lookups.
A dictionary will work for what you are trying to do then.
Dictionary<string, bool> controllerDictionary = new Dictionary<string, bool>();
To set a value
if (controllerDictionary.ContainsKey(controllerName))
controllerDictionary[controllerName] = newValue;
else
controllerDictionary.Add(controllerName, newValue);
To get a value
if (controllerDictionary.ContainsKey(controllerName))
return controllerDictionary[controllerName];
else
//return default or throw exception
You can't to that with an array.
Perhaps you should be using a Dictionary?
A generic dictionary of Dictionary<string,bool> appears to be the kind of thing that will work for your description.
It depends on how you want to use your array. Do you want to look up the value by a key, or by its index? Konamiman suggested a class. But a class with two types is nothing more than a Dictionary<type of key, type of value>.
You can use a dictionary if you want to obtain the value by a key.
Like so:
Dictionary<string, int> MyDict = new Dictionary<string, int>();
MyDict.Add("Brutus", 16);
MyDict.Add("Angelina", 22);
int AgeOfAngelina = MyDict["Angelina"];
Now the disadvantage of a dictionary is that, you can't iterate over it. The order is undetermined. You can not use MyDict[0].Value to obtain the age of Brutus (which is 16).
You could use a
List<KeyValuePair<string, int>> MyList = new List<KeyValuePair<string, int>>();
to iterate through a 2D array of two different types as a List supports iteration. But then again, you cannot obtain the age of Angelina by MyList["Angelina"].Value but you would have to use MyList[0].Value.
But you could use a datatable as well. But it requires somewhat more work to initialize the table with its columns.
If you want to lookup/set a boolean by control name, you could use a Dictionary<string, bool>.
Use Dictionary<string,bool>.
If, for some reason, you really need an array, try object[,] and cast its values to the types you want.
Another way of doing it is to create an array of type object, and then add this to an arraylist.
Here is some sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
object[] o = new object[3];
// Add 10 items to arraylist
for (int i = 0; i < 10; i++)
{
// Create some sample data to add to array of objects of different types.
Random r = new Random();
o[0] = r.Next(1, 100);
o[1] = "a" + r.Next(1,100).ToString();
o[2] = r.Next(1,100);
ar.Add(o);
}
}
}
}
"A multi-dimensional array is an array:
all elementsin all dimensions have the same type"
Actually you can do it with a List. I suggest you take a look at Tuples.
How to easily initialize a list of Tuples?
You can use a list of type object too if you want
Like so :
List<List<object>> Dates = new List<List<object>>() { };
Dates.Add(new List<object>() { 0 ,"January 1st" });

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);

Store Collection of Data Fields and Retrieve Via Identifier

In C#, how can I store a collection of values so if I want to retrieve a particular value later, I can do something like:
myCollection["Area1"].AreaCount = 50;
or
count = myCollection["Area1"].AreaCount;
Generic list?
I'd like to store more than one property to a "key". Is a class the answer?
You're looking for the Dictionary<string, YourClass> class. (Where YourClass has an AreaCount property)
EDIT
Based on your comment, it seems like you want a Dictionary (as already suggested) where your object holds all your 'values.'
For Instance:
public class MyClass
{
public int AreaCount;
public string foo;
public bool bar;
}
//Create dictionary to hold, and a loop to make, objects:
Dictionary<string, MyClass> myDict = new Dictionary<string, MyClass>();
while(condition)
{
string name = getName(); //To generate the string keys you want
MyClass mC = new MyClass();
myDict.Add(name, mC);
}
//pull out yours and modify AreaCount
myDict["Area1"].Value.AreaCount = 50;
Alternatively, you could add a string "Name" to you class (I'm using fields for the example, you'd probably use properties) and use Linq:
//Now we have a list just of your class (assume we've already got it)
myClass instanceToChange = (from items in myList
where Name == "Area1"
select item).FirstOrDefault();
myClass.AreaCount = 50;
Does that help more?
ORIGINAL RESPONSE
I'm not completely sure what you're asking, but I'll give it ago.
Given a list of Objects from which you need to grab a particular object, there are (generally) 4 ways- depending on your specific needs.
The Generic List<T> really only does this well at all if your object already supports some kind of searching (like String.Contains()).
A SortedList uses IComparer to compare and sort the Key values and arrange the list that way.
A Dictionary stores a Key and Value so that KeyValuePair objects can be retrieved.
A HashTable uses Keys and Values where the Keys must implement GetHashCode() and ObjectEquals
The specific one you need will vary based on your specific requirements.
This functionality is provided by indexers

Defining two dimensional Dynamic Array with different types

I want to create two dimension array of different type like I can add to that array two values one of them is controlname and second is boolean value.
You can't do that. Instead, you should create a class that contains these two properties, then you can create an array of that type:
public class MyClass
{
public string ControlName {get;set;}
public bool MyBooleanValue {get;set;}
}
public MyClass[] myValues=new MyClass[numberOfItems];
Or, as Anders says, use a dictionary if one of the properties is meant to be used to perform lookups.
A dictionary will work for what you are trying to do then.
Dictionary<string, bool> controllerDictionary = new Dictionary<string, bool>();
To set a value
if (controllerDictionary.ContainsKey(controllerName))
controllerDictionary[controllerName] = newValue;
else
controllerDictionary.Add(controllerName, newValue);
To get a value
if (controllerDictionary.ContainsKey(controllerName))
return controllerDictionary[controllerName];
else
//return default or throw exception
You can't to that with an array.
Perhaps you should be using a Dictionary?
A generic dictionary of Dictionary<string,bool> appears to be the kind of thing that will work for your description.
It depends on how you want to use your array. Do you want to look up the value by a key, or by its index? Konamiman suggested a class. But a class with two types is nothing more than a Dictionary<type of key, type of value>.
You can use a dictionary if you want to obtain the value by a key.
Like so:
Dictionary<string, int> MyDict = new Dictionary<string, int>();
MyDict.Add("Brutus", 16);
MyDict.Add("Angelina", 22);
int AgeOfAngelina = MyDict["Angelina"];
Now the disadvantage of a dictionary is that, you can't iterate over it. The order is undetermined. You can not use MyDict[0].Value to obtain the age of Brutus (which is 16).
You could use a
List<KeyValuePair<string, int>> MyList = new List<KeyValuePair<string, int>>();
to iterate through a 2D array of two different types as a List supports iteration. But then again, you cannot obtain the age of Angelina by MyList["Angelina"].Value but you would have to use MyList[0].Value.
But you could use a datatable as well. But it requires somewhat more work to initialize the table with its columns.
If you want to lookup/set a boolean by control name, you could use a Dictionary<string, bool>.
Use Dictionary<string,bool>.
If, for some reason, you really need an array, try object[,] and cast its values to the types you want.
Another way of doing it is to create an array of type object, and then add this to an arraylist.
Here is some sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
object[] o = new object[3];
// Add 10 items to arraylist
for (int i = 0; i < 10; i++)
{
// Create some sample data to add to array of objects of different types.
Random r = new Random();
o[0] = r.Next(1, 100);
o[1] = "a" + r.Next(1,100).ToString();
o[2] = r.Next(1,100);
ar.Add(o);
}
}
}
}
"A multi-dimensional array is an array:
all elementsin all dimensions have the same type"
Actually you can do it with a List. I suggest you take a look at Tuples.
How to easily initialize a list of Tuples?
You can use a list of type object too if you want
Like so :
List<List<object>> Dates = new List<List<object>>() { };
Dates.Add(new List<object>() { 0 ,"January 1st" });

Categories