instantiate and initialize multi dimensional array C# - c#

I have a multi dimensional array but i want to be able to instantiate and initialize it in one line does anyone know how to do this?
Here is what i have at the moment.
int[,] Columns = [3,2];
Columns[0,0]= 1;
Columns[1,0]= 0;
Columns[2,0]= 2;
Columns[0,1]= "Distinct";
Columns[1,1]= "Sum";
Columns[2,1]= "Distinct";
im trying to get somthing along the lines of:
If anyone could help it would be much appreciated.

You can, you can use something called a collection initializer with rectangular arrays! But you can't declare the array type as int and try and store strings (such as "Sum") in it too.
You could use the object type to store different data types in the same collection:
object[,] Columns = { { 1, 0, 2 }, { "Distinct", "Sum", "Distinct" } };

Related

Deleting a specific item of an array [duplicate]

This question already has answers here:
Remove element of a regular array
(15 answers)
Closed 9 years ago.
string[] columns
I want to delete the item on an index specified by a variable of type int.
How do I do this ?
I tried
columns.RemoveAt(MY_INT_HERE);
But apparently this does not works.
Array is immutable class, you can't change it, all you can do is to re-create it:
List<String> list = columns.ToList(); // <- to List which is mutable
list.RemoveAt(MY_INT_HERE); // <- remove
string[] columns = list.ToArray(); // <- back to array
May be the best solution is to redesign your code: change immutable array into List<String>:
List<String> columns = ...
columns.RemoveAt(MY_INT_HERE);
If you don't want to use linq you can use this function :
public string[] RemoveAt(string[] stringArray, int index)
{
if (index < 0 || index >= stringArray.Length)
return stringArray;
var newArray = new string[stringArray.Length - 1];
int j = 0;
for (int i = 0; i < stringArray.Length; i++)
{
if(i == index)continue;
newArray[j] = stringArray[i];
j++;
}
return newArray;
}
You use it like that : columns = RemoveAt(columns, MY_INT_HERE)
You can also make it to an extension method.
You cannot delete items in an array, because the length of a C# array is fixed at the time when it is created, and cannot be changed after that.
You can null out the corresponding element to get rid of the string, or use LINQ to produce a new array, like this:
columns = columns.Take(MY_INT_HERE-1).Concat(columns.Skip(MY_INT_HERE)).ToArray();
You need to add using System.Linq at the top of your C# file in order for this to compile.
However, using a List<string> would be a better solution:
List<string> columns;
columns.RemoveAt(MY_INT_HERE);
Try one of the following (depending on what you need):
columns[MY_INT_HERE] = null;
columns[MY_INT_HERE] = string.Empty;
...otherwise you'll just have to create a new array which has a length of 1 less than your current array, and copy the values over.
If you want something more flexible, you might use a something like a List<string>, where you can use RemoveAt()
Arrays are faster for the computer to work with but slower for a programmer. You will have to find that value with a loop or some other means, then set that position to null. You will end up with an empty space in the array. You could reallocate the array etc etc...
What is easier to use for relatively small amounts of data is a List. You can do myList.RemoveAt(100); and it will work nicely.
You can not delete it.You can recreate the array or I advice you to use List<string> for the same.
List<string> columns = new List<string>();
columns.RemoveAt(1);
It will remove the 2nd element from your List<String> columns

Converting from List<float> to int

Can anyone please tell me if this can be done, and if yes, how?
I have a List<float> FocalLengthList that I have populated with some values. Then THIS List is stored in a List<List<float>> MainFocalLenghtList.
However, in my application I need to use the values fromMainFocalLenghtList to update an objects 3D position. So I need to cast fromMainFocalLenghtList [0] to int.
Can this be done and how?
Here is a small section of my code to explain.
Adding values to FocalLengthList then adding that list to List<List<float>> MainFocalLenghtList
float newFocalLength = focalLength * pixelSize;
FocalLengthList.Add(newFocalLength);
MainFocallengthList.Add(FocalLengthList);
FocalLengthList = new List<float>();
Then how I intend to use the values (not working)
int zComponent = MainFocallengthList[0];
You can certainly cast a float to an int, as long as you do so explicitly (since it may involve a loss of precision).
The problem with the code you've posted is that you're indexing into a list of other lists. The value returned by MainFocallengthList[0] will itself be a List<float>. You must then index into that list to get a value you can actually cast to int.
Assuming both the target list and the target float in that list are at the first index of their respective containers:
int zComponent = (int)MainFocalLengthList[0][0];
That first index returns the FocalLengthList that you added to MainFocalLengthList. The second index returns the newFocalLength value that you added to FocalLengthList. Clear? :)
I'd probably do it like this:
int zComponent = (int)Math.Ceiling(MainFocallengthList[m][n]);
Though you'll want to substitute actual values for the nth item in the mth FocalLengthList.
Give this a shot:
var floatList = new List<float>();
var intList = floatList.Select(f => (int)Math.Ceiling(f)).ToList();
Since MainFocalLengthList is a List of List<float>
var intarr = Array.ConvertAll(MainFocalLengthList[0].ToArray(), f=>(int)f);
You can do it this way, but you need the indexes of both the inner and outer lists:
// The first [0] indicates the index of the nested list within MainFocallengthList
// The second [0] indicates the index of the item that you want in the nested list
int zComponent = (int)(MainFocallengthList[0][0])

How to add different types of objects in a single array in C#?

I am planning to rewrite my Python Tile Engine in C#. It uses a list of all the game objects and renders them on the screen. My problem is that unlike in Python where you can add almost anything to an array (e.g x = ["jj" , 1, 2.3, 'G', foo]) you can add only one type of objects
in a C# array (int[] x = {1,2,3};) . Are there any dynamic arrays (similar to the ArrayList() class) or something which allows you to pack different types into a single array? because all the game objects are individual classes.
Very simple—create an array of Object class and assign anything to the array.
Object[] ArrayOfObjects = new Object[] {1,"3"}
you can use an object array. strings, int, bool, and classes are all considered objects, but do realize that each object doesn't preserve what it once was, so you need to know that an object is actually a string, or a certain class. Then you can just cast the object into that class/data type.
Example:
List<object> stuff = new List<object>();
stuff.add("test");
stuff.add(35);
Console.WriteLine((string)stuff[0]);
Console.WriteLine((int)stuff[1]);
Though, C# is a strongly typed language, so I would recommend you embrace the language's differences. Maybe you should look at how you can refactor your engine to use strong typing, or look into other means to share the different classes, etc. I personally love the way C# does this, saves me a lot of time from having to worry about data types, etc. because C# will throw any casting (changing one data type to another) errors I have in my code before runtime.
Also, encase you didn't know, xna is C#'s game framework (didn't have it as a tag, so I assume you aren't using it).
You can write an abstract base class called GameObject, and make all gameObject Inherit it.
Edit:
public abstract class GameObject
{
public GameObject();
}
public class TileStuff : GameObject
{
public TileStuff()
{
}
}
public class MoreTileStuff : GameObject
{
public MoreTileStuff()
{
}
}
public class Game
{
static void Main(string[] args)
{
GameObject[] arr = new GameObject[2];
arr[0] = new TileStuff();
arr[1] = new MoreTileStuff();
}
}
C# has an ArrayList that allows you to mix types within an array, or you can use an object array, object[]:
var sr = new ArrayList() { 1, 2, "foo", 3.0 };
var sr2 = new object[] { 1, 2, "foo", 3.0 };
In c# we use an object[] array to store different types of data in each element location.
object[] array1 = new object[5];
//
// - Put an empty object in the object array.
// - Put various object types in the array.
// - Put string literal in the array.
// - Put an integer constant in the array.
// - Put the null literal in the array.
//
array1[0] = new object();
array1[1] = new StringBuilder("Initialized");
array1[2] = "String literal";
array1[3] = 3;
array1[4] = null;
You can use object[] (an object array), but it would be more flexible to use List<object>. It satisfies your requirement that any kind of object can be added to it, and like an array, it can be accessed through a numeric index.
The advantage of using a List is you don't need to know how items it will hold when you create it. It can grow and shrink dynamically. Also, it has a richer API for manipulating the items it contains.
Here is how you can do it
Use List<object> (as everything is derived from object in C#):
var list = new List<object>();
list.Add(123);
list.Add("Hello World");
Also dynamic might work for you (and your python background)
var list = new List<dynamic>();
list.Add(123);
list.Add(new
{
Name = "Lorem Ipsum"
});
If you wan't to use dynamic you really need to know what you're doing. Please read this MSDN article before you start.
But do you need it?
C# is a strongly-typed and very solid programming language. It is very flexible and great for building apps using object-oriented and functional paradigms. What you want to do may be acceptable for python, but looks pretty bad on C#. My recommendation is: use object oriented programming and try to build model for your problem. Never mix types together like you tried. One list is for a single data-type. Would you like to describe your problem in depth so that we can suggest you a better solution?
In C# 4 and later you can also use dynamic type.
dynamic[] inputArray = new dynamic[] { 0, 1, 2, "as", 0.2, 4, "t" };
Official docu
You can mix specific types doing the following:
(string, int)[] Cats = { ("Tom", 20), ("Fluffy", 30), ("Harry", 40), ("Fur Ball", 40) };
foreach (var cat in Cats)
{
Console.WriteLine(string.Join(", ", cat));
}
You have to declare your array with the datatype object:
object[] myArray = { };
myArray[0] = false;
myArray[1] = 1;
myArray[2] = "test";
You can use an array of object class and all it possible to add different types of object in array.
object[] array = new object[3];
array[0] = 1;
array[1] = "string";
array[3] = 183.54;

How delete an item from struct array in C#

I have a struct in C# and I define and array list of my struct based on my code that I express here. I add items in my array list, but I need to delete a few rows from my list too. Could you help me how can I delete item or items from my struct array list:
public struct SwitchList
{
public int m_Value1, m_Value2;
public int mValue1
{
get { return m_Value1; }
set {m_Value1 = value; }
}
public int mValue2
{
get { return m_Value2; }
set {m_Value2 = value; }
}
}
//Define an array list of struct
SwitchList[] mSwitch = new SwitchList[10];
mSwitch[0].mValue1=1;
mSwitch[0].mValue2=2;
mSwitch[1].mValue1=3;
mSwitch[1].mValue2=4;
mSwitch[2].mValue1=5;
mSwitch[2].mValue2=6;
Now how can I delete one of my items, for example item 1.
Thank you.
Arrays are fixed length data structures.
You will need to create a new array, sized one less than the original and copy all items to it except the one you want to delete and start using the new array instead of the original.
Why not use a List<T> instead? It is a dynamic structure that lets you add and remove items.
You will need to move elements around and resize the array (which is expensive), since there is some complexity there you going to want to hide it in class that just presents the collection without exposing the implementation details of how its stored. Fortunately Microsoft has already provided a class that does just this called List<T> which along with a few other collection types in System.Collections.Generic namespace meet most common collection needs.
as a side note, you should use auto-properties instead of the trivial property style that you ha
That's not possible, because an array is a fixed size block of elements. Because structs are values types and not reference types, you also can't just set the element zo null. One option would be to create a new smaller array and to copy your remaining values to the new array. But the better approach would be to use a List in my opinion.
If you really, really want to use arrays and move things around, here are some examples of how to do it:
{
// Remove first element from mSwitch using a for loop.
var newSwitch = new SwitchList[mSwitch.Length - 1];
for (int i = 1; i < mSwitch.Length; i++)
newSwitch[i - 1] = mSwitch[i];
mSwitch = newSwitch;
}
{
// Remove first element from mSwitch using Array.Copy.
var newSwitch = new SwitchList[mSwitch.Length - 1];
Array.Copy(mSwitch, 1, newSwitch, 0, mSwitch.Length - 1);
mSwitch = newSwitch;
}

Arrays of data classes in C#

I've been messing around with this for ages and I'm not getting any closer.
My current version is as below. The comments are what I think I'm doing.
The semantic is basically an index number (like a house number) and a list of attributes in an array. Then create an array 'street'. I want to be able to update the values of all elements in the current scope. The class is defined as high as possible so as to make the scope global. My ossified 'C' brain doesn't really understand things like lists and IEnumerable so I haven't tried to go that route. The code parser in the editor makes a bit of a mess of this - sorry.
public class house
{
// Ok, looking at this from the world of 'C' and thinking 'struct' like,
// I put my variables here.
public int my_id;
public long [] pl_id;
public house()
{
// I try to initialise the starting values, so I can carry out some tests later.
my_id = 0;
pl_id = new long[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
}
}
// I attempt to inform the compiler that I will be wanting an array of the house objects
// and call that array 'new_house'. Again, the code editor isn't keen.
house [] new_house;
private void button1_Click(object sender, EventArgs e)
{
// In the programs main routine (not *main*!), I then try to get the
// array 'new_house' populated with initialised 'house' objects
for (int idx = 0; idx < 10; idx++)
{
new_house[idx] = new house();
}
// And at some point in the future I wish to set or update the values arbitrarily. eg:
new_house[7].my_id = 123;
new_house[7].pl_id = 345678;
// any combination of attributes and id numbers is possible, so I use zero simply to see if they have been set, with -1 indicating failure / an absence of data-
}
}
Right. As I say, I've tried a lot of different ways to do this, and the main problem I am getting is that I never seem to correctly initialise the array 'new_house' and get null exceptions thrown when I try to assign anything. I can't believe something that seems so intuitively simple can be so hard to code, so where have I got it wrong (and I fully accept that there could be more than one conceptual or coding error in the above).
Comments on appropriateness of approach, and help with coding alike, gratefully accepted.
You need to instantiate the array before initializing items of it:
house[] new_house = new house[10];
Replace 10 with desired number of items.
In case you don't know the number, use List:
List<house> new_house = new List<house>()
Then you can dynamically add items using new_house.Add(item) and access them in foreach loop or through index new_house[i]
The first obvious problem with your code is that your constructor doesn't have the same name as the class. It should be this:
public house()
{
// ...
}
A second point is you don't need the constructor at all here:
public int my_id = 0; // The "= 0" is actually not needed here either.
public long[] pl_id = new long[10];
I would also suggest that you don't use arrays for things like houses on a street because house numbers won't necessarily be sequential. You can have gaps and even multiple houses with the "numbers" 5A and 5B. A dictionary might be a better choice.
IDictionary<string, house> houses = new Dictionary<string, house>();
If you really want to have sequential numbering you might want to consider a List<house> instead of an array so that it can be easily extended if new houses are built.
Finally I'd advise using PascalCase for classes. It will make your code much easier to read if you use the same standards as the rest of the .NET framework.
Change public game()
to public house()
Your constructor has to have the same name as the class.
A couple things:
new_house is never initialized. You can't use it until you've initialized it.
pl_id is an array, but you attempt to store a long in it (345678) -- you could change it to new int[] { 345678}.
You've got a method, game(), in the class house which looks and acts like a constructor. You would have to name it house() if it is meant to be a constructor.
not public game()
right: public house()
Always the constructor has to have the same name as the class.
Use List<T> for those collections. Try not to say you don't understand something because you are 'c' addicted. Try to say yourself you want to try something new and search for a good solution
namespace Myprog
{
// I attempt to inform the compiler that I will be wanting an array of the house objects
// and call that array 'new_house'
List<house> houselist = new List<house>();
private void button1_Click(object sender, EventArgs e)
{
// In the programs main routine (not *main*!), I then try to get the
// array 'new_house' populated with initialised 'house' objects
for (int idx = 0; idx < 10; idx++)
{
houselist.add(new house());
}
// And at some point in the future I wish to set or update the values arbitrarily. eg:
houselist[7].my_id = 123;
// any combination of attributes and id numbers is possible, so I use zero simply to see if they have been set, with -1 indicating failure / an absence of data-
}
}
}

Categories

Resources