I'm using jagged arrays and have a bit of a problem (or at least I think I do). The size of these arrays are determined by how many rows are returned in a database, so it is very variable. The only solution I have is to set the dimensions of the array to be very huge, but this seems ... just not the best way to do things.
int[][] hulkSmash = new int[10][];
hulkSmash[0] = new int[2] {1,2};
How can I work with jagged arrays without setting the dimensions, or is this just a fact of life with C# programming??
You've got 2 choices:
You can read the size of the information returned from the database, and allocate your array space at that time, once you know what you're getting.
Otherwise, what you're looking for is a data structure that has variable dimensions. Take a look at List for example: MSDN: List< T >
The other examples using List<T> and collections are the best way to proceed. I sometimes find the
List<List<int>> hulkSmash = new List<List<int>>();
syntax a tad unwieldy. Luckily, there are some options to manage this.
The first option I sometimes use is to make an alias:
using List<List<int>> = HulkSmashCollection;
This prevents you from having to do nested <<<Types>>> all the time. Everywhere you'd type List<List<int>> you can instead type HulkSmashCollection (or something shorter still) instead.
The second option is to wrap the List of Lists within a class called, say, MyHulkSmashes. Here, you only provide the functions/properties you need, like Count or Find() etc.
Both these concepts are used to reduce the amount of code on screen, and reduce perceived complexity.
List<List<int>> hulkSmash = new List<List<int>>();
hulkSmash.Add(new List<int>() { 1, 2 });
or
List<int[]> hulkSmash = new List<int[]>();
hulkSmash.Add(new int[] { 1, 2 });
A collection of ints (such as List) will give you the flexibility that you want and not waste space as would allocating an array that is much larger than you will ever need.
Related
Needed to store many varbiables and at first went with an array, but I had errors when I tried to resize the amount of positions in an array with a separate variabe. Looked online and people said, better use a List.
I have but very confusing to use. Trying to use it logically but I'm just not getting it.
So I set up my list:
public List<int> TESTValues = new List<int>(10);
And to me logically, there should be a list on 10 positions but there isn't, it's empty. Only does it add a variable if I use: TESTValues.Add(1); which only adds 1 new variable in the next available position which is 1 when it should be position 11 right?
Let's say I would somehow get a list of 10 variables, how would I then reference a variable in position 8 of the list, even update it? I tried to use something like: TESTValues.IndexOf(8) = 40; sadly that does not work.
Anyone have a good understanding of these Lists and how I could get to use them? Explain them? Was expecting a List to be simpley than an Array, seems the other way round right now.
Capacity != Size (Count)
Gets or sets the total number of elements the internal data structure can hold without resizing.
The initial capacity given to the constructor has only one purpose: Immediate allocation.
Usually by default a List<T> starts with an initial capacity of 4. Under the hood it simply stores the values in an array.
Then every time you add elements and the new size would exceed the capacity then the underlying array is copied into a new array with double of the original size (= capacity of the list).
The "size" (= Count of the list) only grows by adding elements!
Gets the number of elements contained in the List<T>.
Now the only way to initialize a list with already 10 elements is by using another collection like e.g.
var yourList = new List<int>(new int[10]);
of course this requires the allocation of an array => work for the GC but if you do this only once probably not very problematic.
or using Linq you could also do
using System.Linq;
...
var yourList = Enumerable.Repeat(0, 10).ToList();
I am trying to create a jagged array but due to the dynamic-ness of the data I am working with I do not want to waste resources creating a a large jagged array.
I am currently doing:
int[][][] data = new data[Int16.MaxValue][][];
I do not how big the data set is, or is there a better way than doing it via Lists?
Yes, you should use List<T>.
In this case, you would use List<List<List<int>>>.
Your array:
int[][][] data = new data[Int16.MaxValue][Int16.MaxValue][Int16.MaxValue];
will take up (2^16)^3 = 2^48 = way more storage space than you have,
not to mention that that declaration is not valid C#.
If you don't know how much space you need when you initialize, then it would be best to use a dynamically resizing list.
Use a variable similar to this:
List<List<List<int>>> data = new List<List<List<int>>>();
This variable allows you to add List<List<int>>'s to it, and those lists contain List<int>'s, which of course contain int's
If you absolutely do not want to use Lists, you can always replicate what Lists do under the hood: Create your array with a small number of elements, and when you reach the maximum, create a new array that is double the original's size, copy your existing array into it, and dispose of your original. Continue this pattern until you are done. I recommend using Lists instead, but this is how you would get around it if, for some reason, you just don't want to use Lists.
In fact, you can create jagged arrays without defining second and further dimensions.
int[][][] jagged = new int[256][][];
But at large datasets it is more effective to use streaming data - i.e., combinations of IEnumerable<T>.
very basic question, but is there any ToArray-like function for c# linked lists that would return an array of only part of the elements in the linkedlist.
e.g.: let's say my list has 50 items and I need an array of only the first 20. I really want to avoid for loops.
Thanks,
PM
Use Linq?
myLinkedList.Take(20).ToArray()
or
myLinkedList.Skip(5).Take(20).ToArray()
You say you "really want to avoid for loops" - why?
If you're using .NET 3.5 (or have LINQBridge), it's really easy:
var array = list.Take(20).ToArray();
... but obviously that will have to loop internally.
Note that this will create a smaller array if the original linked list has fewer than 20 elements. It's unclear whether or not that's what you want.
Something is going to have to loop internally, sooner or later - it's not like there's going to be a dedicated CPU instruction for "navigate this linked list and copy a fixed number of pointers into a new array". So the question is really whether you do it or a library method.
If you can't use LINQ, it's pretty easy to write the equivalent code yourself:
int size = Math.Min(list.Count, 20);
MyType[] array = new MyType[size];
var node = list.First;
for (int i = 0; i < size; i++)
{
array[i] = node.Value;
node = node.Next;
}
That will actually be slightly more efficient than the LINQ approach, too, because it creates the array to be exactly the right size to start with. Yes, it uses a loop - but as I say, something's got to.
If you're using the LinkedList collection class (from System.Collections.Generic), you can use LINQ to get it:
var myArray = list.Take(20).ToArray();
With a 1D array, I can use the sum method to get the sum of all the values.
int[] array = {6,3,1};
Console.WriteLine(array.Sum());
With a multidimensional array (3D in my case), this can't be done. Obviously I could go all foreach on it, but this seems verbose and I suspect it will perform badly.
Is there a way to flatten the array? Or a nice way just to get the sum that I've not seen?
Sum does exactly foreach. There is no magic behind them. If you are so performance hungry use for instead of foreach. You can do this in parallel also, this operation can be easily parallelized.
this'll do the trick.
var i = array.SelectMany(j => j).Sum()
you could parallelize this in .net 4 like this
var i = array.AsParallel().SelectMany(k => k).Sum();
Why should a foreach perform badly? You have to read every value at least once to calculate the sum. There is no way around this (assuming "random" values, of course). So maybe there is a more beautyful way, but not a more performant one (speaking in terms of Big O).
If you have a jagged array and would like clean code you could use
int[][] array = { new []{ 6, 3, 1 }, new []{ 6, 3, 1 } };
Console.WriteLine(array.Sum(i => i.Sum()));
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];