I have to copy the following int array in to Array :
int[] intArray=new int[] {10,34,67,11};
i tried as
Array copyArray=Array.CreateInstance(typeof(int),intArray.Length,intArray);
intArray.CopyTo(copyArray,0);
But ,it seems i have made a mistake,so i did not get the result.
This works:
int[] intArray = new int[] { 10, 34, 67, 11 };
Array copyArray = Array.CreateInstance(typeof(int), intArray.Length);
intArray.CopyTo(copyArray, 0);
foreach (var i in copyArray)
Console.WriteLine(i);
You had one extra "intArray" in your Array.CreateInstance line.
That being said, this can be simplified if you don't need the Array.CreateInstance method (not sure if that's what you're trying to work out, though):
int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = new int[intArray.Length];
intArray.CopyTo(copyArray, 0);
Even simpler:
int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = (int[])intArray.Clone();
Are you aware that an int[] is already an Array? If you just need to pass it to something accepting Array, and you don't mind if it changes the contents, just pass in the original reference.
Another alternative is to clone it:
int[] clone = (int[]) intArray.Clone();
If you really need to use Array.CopyTo then use the other answers - but otherwise, this route will be simpler :)
Try this instead:
int[] copyArray = new int[intArray.Length];
Array.Copy(intArray, copyArray, intArray.Length);
In this particular case, just use
int[] copyArray = (int[]) intArray.Clone();
Related
I can not understand the difference between the declaration with array initialization in the first case and the second
int[] array = new int[3] { 1, 2, 3 };
int[] secondArray = { 1, 2, 3 };
They seem to do the same thing, maybe they work differently?
The is no difference in the result between the two show lines shown:
int[] array = new int[3] { 1, 2, 3 };
int[] secondArray = { 1, 2, 3 };
However, there are practical differences between new int[n] {...} syntax and {...}:
Implicit type is not available for the alternative array initialiser:
var a1 = new int[3] { 1, 2, 3 }; // OK
var a2 = { 1, 2, 3 }; // Error: Cannot initialize an implicitly-typed variable with an array initializer
// BTW. You can omit the size
var a3 = new int[] { 1, 2, 3 }; // OK
With the alternative syntax you cannot specify the size, it's always inferred.
var a1 = new int[100]; // Array with 100 elements (all 0)
int[] a2 = { }; // Array with no elements
There is no difference in the compiled code between the two lines.
The second one is just a shortcut. Both statements have the same result. The shorter variant just wasn't available in early versions of C#.
The first one uses 3 as a array size explictly, the 2nd one size is inferred.
This might be work if you dont want to initialize the values.
There is no difference between this two array initialization syntaxes in terms how they will be translated by the compiler into IL (you can play with it at sharplab.io) and it is the same as the following one:
int[] thirdArray = new int[] { 1, 2, 3 };
The only difference comes when you are using those with already declared variable, i.e. you can use 1st and 3rd to assign new value to existing array variable but not the second one:
int[] arr;
arr = new int[3] { 1, 2, 3 }; // works
// arr = { 1, 2, 3 }; // won't compile
arr = new int[] { 1, 2, 3 }; // works
This is such a simple question, but I cannot find the answer.
What I am looking for is the lightweight way of enumerating through a list of integers without having to define a new array or list or something. The code shown below represents what I want to do, but it doesn't work.
var x = from z in [] {1, 19, 64, 128, 132}
select new {z, "asdffdghdfgh" };
The bit I need help with, without creating something horrible or another variable, is the {1, 19, .... } inline
Thanks
John
In order to do so you must still instantiate an array. This still allocates the object but you just don't have any reference to it after the query is executed.
// See addition of `new int[]`
var x = from z in new int[] { 1, 19, 64, 128, 132 }
select new { z, x = "someText" };
If you were creating a string[] then you wouldn't have to specify the string word before the [] but you would still have to write new [] {...}
I have two arrays, one singular and the other 2 dimensional.
int[][] array1 = {
new int [] {1, 22, 3, 44, 5, 66},
new int [] {11, 22, 33, 44, 55, 66},
new int [] {1, 2, 3, 4, 5, 6},
};
int[] array2 = new int[] {1, 2, 3, 5, 66}
I need to create a loop which searches the array1 for both the 2nd last digits in array2, so it would return how many times an array with array1 contains both 5 and 66, which is 1, as the other two only contain 1 of each number.
I already managed to write a function which returns how many times array2 as a whole exists in array1, this new function is effectively a refinement of that.
for (int a = 0; a < array1[i].Length; a++)
{
for (int b = 0; b < array2.Length; b++)
{
if (array2[c] == array1[a][b])
count++;
temp[b] = array1[a][b];
}
}
I feel all would be needed to search for just the last two digits is a slight change to this function, I tried to add in another loop but that didn't work either. How would I go about doing this? I'm using loops and not Contains for a reason since i'm still learning the basics.
The one thing is not clear in question that, does it matter which position the two digits occur in the 2D array?
If ithis is not the case, then you can use Intersect() which produces the set intersection of two sequences by using the default equality comparer to compare values:
var result = array1.Count(x => x.Intersect(array2.Reverse().Take(2)).Count() == 2);
If you have paid an attention we have used this line, for getting last two elements of array1:
array1.Reverse().Take(2);
.NET Fiddle
Additional:
If you want to find if last two elements of arrays in 2D array is equal to last two elements of array1, then you can try LINQ solution:
var result = array1.Count(x=> x.Reverse().Take(2).SequenceEqual(array2.Reverse().Take(2)));
Explanation of used extension methods:
Reverse() inverts the order of the elements in a sequence.
Take() returns a specified number of contiguous elements from the start of a sequence.
SequenceEqual() determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
After getting last two elements of both arrays, we will use SequenceEqual() to determine if both arrays are equal.
var res = array1.Where((x) => (x.Contains(array2.Last()) && x.Contains(array2[array2.Length - 2]))).Count();
Explaination:
array1.Where takes every subarray of array1 and filters the ones that
meet a certain condition. The condition being every subarray of
array1 contains the last && next-to-last element of array2.The
Count() methods returns the number of subarrays that meet the
conditions
You can create an array of target values and then count the number of times that the intersection of that array with each subarray in the 2D array contains all the items in the target array:
using System;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
[STAThread]
private static void Main()
{
int[][] array1 =
{
new [] {1, 22, 3, 44, 5, 66},
new [] {11, 22, 33, 44, 55, 66},
new [] {1, 2, 3, 4, 5, 6},
new [] {1, 66, 3, 4, 5, 6} // This one has the target items out of order.
};
int[] array2 = {1, 2, 3, 5, 66};
// Extract the targets like this; it avoids making a copy
// of array2 which occurs if you use IEnumerable.Reverse().
int[] targets = {array2[array2.Length - 2], array2[array2.Length - 1]};
// Count the number of times that each subarray in array1 includes
// all the items in targets:
int count = array1.Count(array => array.Intersect(targets).Count() == targets.Length);
Console.WriteLine(count);
}
}
}
I'm working on a project. I've a situation here. I'm having arrays with similar names consider arr1, arr2, arr3, etc.
Now I know the array number which I'm supposed to use let it be 2. Is there any way in c# to make the array name dynamically through strings and use it.
Like in flash action script we can do
_root["arr"+i][0]
here i contains the array number to be used.
No - you cannot access variable names dynamically. You can use reflection to dynamically access properties, but not variables. I would use a List<int[]> like so:
List<int[]> arrList = new List<int[]> {arr1, arr2, arr3);
int[] arr = arrList[i-1]; // since lists and arrays use 0-based indexes
You can use a dictionary:
var dictionary = new Dictionary<string, int[]>();
dictionary.Add("array1", arr1);
dictionary.Add("array2", arr2);
dictionary.Add("array3", arr3);
var arr = dictionary[string.Format("array{0}", i)];
What you want is something what JavaScript or dynamic languages have, but their array types are rather associative arrays. To reach the functionality you want you can use Dictionary:
var arr1 = new int[] { 0, 1, 2, 3 };
var arr2 = new int[] { 0, 1, 2, 3 };
var arr3 = new int[] { 0, 1, 2, 3 };
var _root = new Dictionary<string, int[]>();
_root.Add("arr1", arr1);
_root.Add("arr2", arr2);
_root.Add("arr3", arr3);
for (int i = 1; i <= 3; i++)
{
int arrElem = _root["arr" + i][0];
}
Note the expression within the for loop, it's like what you were asking for.
use list for performing dynamic operations
As suggested in other answers the way to achieve the dynamism you're looking for is to put all of the arrays in a collection ( List<int[]> ) and then you can write more generalized code which operates on the contents of a given array without knowing which array it's operating on at compile time.
Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?
int nums=5;
int[] array= new int[nums];
for(int i=0;i<num;i++)
{
array[i] = i;
}
Maybe with linq or some array.function?
int[] array = Enumerable.Range(0, nums).ToArray();
Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;
int[] array = Enumerable.Range(0, nums).ToArray();
Generates a sequence of integral numbers within a specified range.
Using Enumerable.Range
int[] array = Enumerable.Range(0, nums).ToArray();
Maybe I'm missing something here, but here is the best way I know of:
int[] data = new int [] { 383, 484, 392, 975, 321 };
from MSDN
even simpler:
int[] data = { 383, 484, 392, 975, 321 };