How do you insert a value into an array, preserving order? - c#

I have a string array, and I want to add a new value somewhere in the center, but don't know how to do this. Can anyone please make this method for me?
void AddValueToArray(String ValueToAdd, String AddAfter, ref String[] theArray) {
// Make this Value the first value
if(String.IsNullOrEmpty(AddAfter)) {
theArray[0]=ValueToAdd; // WRONG: This replaces the first Val, want to Add a new String
return;
}
for(int i=0; i<theArray.Length; i++) {
if(theArray[i]==AddAfter) {
theArray[i++]=ValueToAdd; // WRONG: Again replaces, want to Add a new String
return;
}
}
}

You can't add items to an array, it always remains the same size.
To get an array with the item added, you would need to allocate a new array with one more item, and copy all items from the original array to the new array.
This is certainly doable, but not efficient. You should use a List<string> instead, which already has an Insert metod.

This would work only in some particular case.
public static void AddValueToArray(ref String[] theArray, String valueToAdd, String addAfter) {
var count=theArray.Length;
Array.Resize(ref theArray, 1+count);
var index=Array.IndexOf(theArray, addAfter);
var array=Array.CreateInstance(typeof(String), count-index);
Array.Copy(theArray, index, array, 0, array.Length);
++index;
Array.Copy(array, 0, theArray, index, array.Length);
theArray[index]=valueToAdd;
}
Here's a sample, but it works with Type, you might need to modify the type you need. It is an example of copying array recursively.
How to find the minimum covariant type for best fit between two types?

See how IList Insert method is implemented

Related

implementation of insert function of Bucket hashing algorithm

In the code below, doesn't it say, "if the array list does not contain the item then add it"?
public void Insert(string item)
{
int hash_value;
hash_value = Hash(value);
if (data[hash_value].Contains(item))
data[hash_value].Add(item);
}
If the item is already there, then why is it adding it again?
The code as written says, "if the collection at the index of the hash of "value" contains "item", then try to add it again". You're missing a '!' in front of your if condition (which means "not"), like this:
public void Insert(string item)
{
int hashValue = Hash(value);
if (!data[hashValue].Contains(item)) data[hashValue].Add(item);
}
Note that in your code snippet, value is undefined. It is entirely possible that you could get an IndexOutOfRangeException if hashValue is greater than the number of items in the collection.
Also, data is undefined, so it's also possible that the item at data[hashValue] is null, in which case you'll get a NullReferenceException when trying to call .Contains() on it.
There are different ways to handle these issues, depending on the datatype of data. If it's an array of lists, for example, you could just not add anything if the hash is out of range, and you can initialize the list if it's null:
public void Insert(string item)
{
int hashValue = Hash(value);
if (hashValue < data.Length)
{
if (data[hashValue] == null) data[hashValue] = new List<string>();
if (!data[hashValue].Contains(item)) data[hashValue].Add(item);
}
}

How to dynamically resize an array?

I have an array with Length = 3 and with values, for example {1,2,3}.
I need to dynamically resize it.
I know that I can use List or
Array.Resize(). But I need to know how to implement my own resize method?
You can try the following code. Create new array with new size and copy the old array data to the newly created array.
public static Array ResizeArray (Array oldArray, int newSize)
{
int oldSize = oldArray.Length;
Type elementType = oldArray.GetType().GetElementType();
Array newArray = Array.CreateInstance(elementType,newSize);
int preserveLength = System.Math.Min(oldSize,newSize);
if (preserveLength > 0)
{
Array.Copy (oldArray,newArray,preserveLength);
}
return newArray;
}
If this is just for practice then do it. but i suggest you use .Net Array.Resize() if you want to use it in your code. usually .Net libraries are best implemented and optimized.
Any way...you can do it with generic method
private static void Resize<T>(ref T[] array,int size)
{
T[] token = array.Take(size).ToArray(); // attempt to take first n elements
T[] temp = new T[size]; // create new reference
token.CopyTo(temp, 0); // copy array contents to new array
array = temp; // change reference
}
Note that you cannot do this without parameter ref. (The other way is to return array of course)
You may think arrays are passed by reference. thats true. But the references it self are passed by value. so whenever you try to change the reference it does not refer to the original array anymore. you can only change the contents. To make this possible you have to use ref to directly pass the reference into method.
About the code:
{1,2,3} if you resize it to 2 obviously it will remove the last parameter. so you will have {1,2}
if you resize it to 4 then it will give the array with new default values. either null for reference types or 0 for value types (false for Boolean type). here you will have {1,2,3,0}
int[] array = new[] {1, 2, 3};
Resize(ref array,4);
Console.WriteLine(array.Length); // outputs 4
Well, you may look on Array.Resize source code before making your own implementation =)
http://referencesource.microsoft.com/#mscorlib/system/array.cs,71074deaf111c4e3
If you want to resize the array use the build in method Array.Resize().It will be easier and faster.
If you need a dynamically sized data structure, use List for that.
You can always do array.ToList() -> fill the list and do .ToArray() later.
Make an array of the new desired size, copy all items over. Make the variable that referenced your old array reference the new one.
Code from MSDN:
public static void Resize<T>(ref T[] array, int newSize) {
if (newSize < 0) {
throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.ValueAtReturn(out array) != null);
Contract.Ensures(Contract.ValueAtReturn(out array).Length == newSize);
Contract.EndContractBlock();
T[] larray = array;
if (larray == null) {
array = new T[newSize];
return;
}
if (larray.Length != newSize) {
T[] newArray = new T[newSize];
Array.Copy(larray, 0, newArray, 0, larray.Length > newSize? newSize : larray.Length);
array = newArray;
}
}
}

Convert dictionary of any type to IEnumerable collection

I've written some code to output any IEnumerable collection to a file, but can't pass dictionaries to it. I'm now trying to convert the dictionary (which might be int, int or int, string or any other combination) into an array so I can do this. The code below indicates an error when I try to pass it to the method requiring the IEnumerable.
Generics are something I haven't done much with so perhaps I've done something wrong with those.
public static bool DictionaryToFile<T, U>(Dictionary<T, U> TheDictionary, string FilePath)
{
long count = 0;
string[,] myArray = new string[2,TheDictionary.Count];
foreach (var current in TheDictionary)
{
myArray[0, count] = current.Key.ToString();
myArray[1, count] = current.Value.ToString();
}
// error appears here
TypedListToFile<string[,]>(myArray, FilePath);
return true;
}
The other one I'm calling:
public static bool TypedListToFile<T>(IEnumerable<T> TypedList, string FilePath)
It really depends on what you are trying to do: when you read: Why do C# Multidimensional arrays not implement IEnumerable<T>? You'll see that a multidimensional array doesn't implement IEnumerable, so you have to convert it first. Yet, your code doesn't make sense. I assume you need to increment count in your loop?
Now as for solutions: you can simulate VB behaviour which automatically converts multi-dimensional arrays into enumerables by applying a linq query over it. like:
var arrayEnumerable = from entry in myArray select entry;
// and some proof that this works:
foreach (string entry in arrayEnumerable)
{
// this will succesfully loop your array from left to right and top to bottom
}
TypedListToFile<string[,]>(myArray, FilePath);
The type of myArray is not IEnumerable<string[,]>, so myArray can't be the first parameter to this method.

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

C#: Setting all values in an array with arbitrary dimensions

I'm looking for a way to set every value in a multidimensional array to a single value. The problem is that the number of dimensions is unknown at compile-time - it could be one-dimensional, it could be 4-dimensional. Since foreach doesn't let you set values, what is one way that I could achieve this goal? Thanks much.
While this problem appears simple on the surface, it's actually more complicated than it looks. However, by recognizing that visiting every position in a multidimensional (or even jagged) array is a Cartesian product operation on the set of indexes of the array - we can simplify the solution ... and ultimately write a more elegant solution.
We're going to leverage Eric Lippert's LINQ Cartesian Product implementation to do the heavy lifting. You can read more about how that works on his blog if you like.
While this implementation is specific to visiting the cells of a multidimensional array - it should be relatively easy to see how to extend it to visit a jagged array as well.
public static class EnumerableExt
{
// Eric Lippert's Cartesian Product operator...
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct =
new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }));
}
}
class MDFill
{
public static void Main()
{
// create an arbitrary multidimensional array
Array mdArray = new int[2,3,4,5];
// create a sequences of sequences representing all of the possible
// index positions of each dimension within the MD-array
var dimensionBounds =
Enumerable.Range(0, mdArray.Rank)
.Select(x => Enumerable.Range(mdArray.GetLowerBound(x),
mdArray.GetUpperBound(x) - mdArray.GetLowerBound(x)+1));
// use the cartesian product to visit every permutation of indexes
// in the MD array and set each position to a specific value...
int someValue = 100;
foreach( var indexSet in dimensionBounds.CartesianProduct() )
{
mdArray.SetValue( someValue, indexSet.ToArray() );
}
}
}
It's now trivial to factor this code out into a reusable method that can be used for either jagged or multidimensional arrays ... or any data structure that can be viewed as a rectangular array.
Array.Length will tell you the number of elements the array was declared to store, so an array of arrays (whether rectangular or jagged) can be traversed as follows:
for(var i=0; i<myMDArray.Length; i++)
for(var j=0; j < myMDArray[i].Length; i++)
DoSomethingTo(myMDArray[i][j]);
If the array is rectangular (all child arrays are the same length), you can get the Length of the first array and store in a variable; it will slightly improve performance.
When the number of dimensions is unknown, this can be made recursive:
public void SetValueOn(Array theArray, Object theValue)
{
if(theArray[0] is Array) //we haven't hit bottom yet
for(int a=0;a<theArray.Length;a++)
SetValueOn(theArray[a], theValue);
else if(theValue.GetType().IsAssignableFrom(theArray[0].GetType()))
for(int i=0;i<theArray.Length;i++)
theArray[i] = theValue;
else throw new ArgumentException(
"theValue is not assignable to elements of theArray");
}
I think there is no direct way of doing this, so you'll need to use the Rank property to get the number of dimensions and a SetValue method (that takes an array with index for every dimension as argument).
Some code snippet to get you started (for standard multi-dimensional arrays):
bool IncrementLastIndex(Array ar, int[] indices) {
// Return 'false' if indices[i] == ar.GetLength(i) for all 'i'
// otherwise, find the last index such that it can be incremented,
// increment it and set all larger indices to 0
for(int dim = indices.Length - 1; dim >= 0; dim--) {
if (indices[dim] < ar.GetLength(dim)) {
indices[dim]++;
for(int i = dim + 1; i < indices.Length; i++) indices[i] = 0;
return;
}
}
}
void ClearArray(Array ar, object val) {
var indices = new int[ar.Rank];
do {
// Set the value in the array to specified value
ar.SetValue(val, indices);
} while(IncrementLastIndex(ar, indices));
}
The Array.Clear method will let you clear (set to default value) all elements in a multi-dimensional array (i.e., int[,]). So if you just want to clear the array, you can write Array.Clear(myArray, 0, myArray.Length);
There doesn't appear to be any method that will set all of the elements of an array to an arbitrary value.
Note that if you used that for a jagged array (i.e. int[][]), you'd end up with an array of null references to arrays. That is, if you wrote:
int[][] myArray;
// do some stuff to initialize the array
// now clear the array
Array.Clear(myArray, 0, myArray.Length);
Then myArray[0] would be null.
Are you saying that you want to iterate through each element and (if available) each dimension of an array and set each value along the way?
If that's the case you'd make a recursive function that iterates the dimensions and sets values. Check the Array.Rank property on MSDN and the Array.GetUpperBound function on MSDN.
Lastly, I'm sure generic List<T> has some sort of way of doing this.

Categories

Resources