is there a function equivalent of php array_merge in c# - c#

If not what's the best way to create it ?
Note: merging is not just appending, it fusionned keys that are the same.

This functionality exist on a List element. Arrays are fixed width items in C#, so you can't modify the size without creating a new array. However, Lists are a different story. You can do:
List<int> sample = oldList.AddRange(someOtherList);
// sample contains oldList with all elements of someOtherList appended to it.
Additionally, with LINQ it's trivially easy to convert between List and Array with the
.ToList()
.ToArray()
extension methods. If you want to do that with an indeterminate number of arrays, you could do something like this:
public static class ArrayExtensions
{
public static T[] MergeArrays<T>(this T[] sourceArray, params T[][] additionalArrays)
{
List<int> elements = sourceArray.ToList();
if(additionalArrays != null)
{
foreach(var array in additionalArrays)
elements.AddRange(array.ToList());
}
return elements.ToArray();
}
}
And call:
int[] mergedArray = initialArray.MergeArrays(array1, array2, array3 /* etc */);

You can use the LINQ Concat() method:
using System.Linq;
// ...
var arr1 = new[] { 1, 2, 3 };
var arr2 = new[] { 4, 5, 6 };
var merged = arr1.Concat(arr2); // This returns an IEnumerable<int>
// If you want an actual array, you can use:
var mergedArray = merged.ToArray();

Duplicate. Already discussed here:
Most efficient way to append arrays in C#?
You can't merge arrays as arrays have fixed size in C#. There are numerous ways to do this with enumerables and List.

No not directly equivalent to array_merge.
If you just want to merge two arrays there is already another question : Merging two arrays in .NET
If your looking for a direct array merge replacement there is none.

Related

Getting the number of elements in a generic array

For a school project, I need to return the number of elements in a generic array (a T[] array).
In the constructor I set the array like this:
T[] arr = new T[100];
arr.add(3);
arr.add(2);
arr.add(1);
To find the size of the array I tried array.length, however this return the capacity which would be 100 but it should be 3.
How could I find the correct answer 3?
EDIT:
The add function is a simple function that checks if the size is smaller than default_capacity add data to array. Size variable is crucial and the function expects the total number of elements in the array.
public void Add(T x)
{
if(size < DEFAULT_CAPACITY)
{
array[size] = x;
}
}
Here the array has not a capacity of 100: it has 100 items.
An array has no capacity, it has Length items...
For example, an array of 100 integers has 100 boxes initialized to 0.
And an array has no add method...
You may use a List<T> instead and you'll have Count property and Add method.
List<> is more smooth and usefull than arrays, but a little less optimized.
If the work is to use a such initialized array, you may use #itsme86 advice in question comment.
But here what is add method in your code?
You can use your intended array like that:
public class GenericArray<T>
{
public readonly T[] arr = new T[100];
}
var myArray = new GenericArray<int>();
myArray.arr[0] = 3;
myArray.arr[1] = 2;
myArray.arr[10] = 1;
And you still have 100 items: myArray.arr.Length is 100.
You can use a generic list like that:
public class GenericList<T>
{
public readonly List<T> list = new List<T>(100);
}
var myList = new GenericList<int>();
myList.list.Add(3);
myList.list.Add(2);
myList.list.Add(1);
And here you have 3 items: myList.list.Count is 3.
The list has here a capacity of 100: it means you can add items without resizing the internal array.

Array as property. Looking for simpler way to fill an array

I am pretty new to C# and I see a lot of code where I'm not quite familiar with the syntax. So I was wondering if there's some simpler way of doing what I did here:
I have a class with various properties and functions. One of them is public int gettypeforitem(int i) which returns an integer.
I want to define a property of type int[] that returns an array of the types of all items.
I come from C++, so the following code seems logic to me, but I was wondering if there's a more "straight forward" way in doing this in C#.
Thank you!
public int[] type
{
get
{
List<int> _list = new List<int>();
for(uint i=0; i<NumberOfItems;i++)
_list.Add(gettypeforitem(i));
return _list.ToArray();
}
}
LINQ is the way forward here, I'd say:
public int[] Types => Enumerable.Range(0, NumberOfItems)
.Select(i => GetTypeForItem(i))
.ToArray();
I've changed the names to follow .NET naming conventions, and this is using C# 6's expression-bodied property syntax.
As this is doing a relatively large amount of work for a property - generating a new array every call, for a start - you might want to consider making it a method instead:
public int[] GetTypes() => Enumerable.Range(0, NumberOfItems)
.Select(i => GetTypeForItem(i))
.ToArray();
As noted in comments elsewhere, you may be able to use a method group conversion for the argument to the Select method:
public int[] GetTypes() => Enumerable.Range(0, NumberOfItems)
.Select(GetTypeForItem)
.ToArray();
The exact rules for when method group conversions are valid as arguments always elude me, so I won't try to summarise them here. (They've changed over time, too.)
public int[] type
{
get
{
return Enumerable.Range(0, NumberOfItems).Select(gettypeforitem).ToArray();
}
}
Update:
As suggested in comments its better to keep C# naming standards:
public int[] Types
{
get
{
return Enumerable.Range(0, NumberOfItems).Select(getTypeForItem).ToArray();
}
}
Since you know the number of items, you can create an array straight away:
int[] _arr = new int[NumberOfItems];
for(uint i=0; i<NumberOfItems;i++)
_arr[i] = gettypeforitem(i);
return _arr;
Or if you don't care about the overhead:
Enumerable.Range(0, NumberOfItems).Select(gettypeforitem).ToArray();
Does the return type of the property have to be really an array? If not, you can alternatively also use this:
public IEnumerable<int> type
{
get
{
for(uint i=0; i<NumberOfItems;i++)
yield return gettypeforitem(i);
}
}
and then:
myObject.type.ToArray();

any way to compare an integer variable to a list of integers in if statement

I am wondering if there is a way to compare an integer variable to a list of integers in if statement as we can do it in SQL WHERE CLAUSE,
WHERE MY_ID IN (1,2,3,4,5,6)
and I want to use the same functionality if it exists in c#
if(myid in (1,2,3,4,5,6)){}
this might seem a dummy question but it would save me a lot of time if existed
You can use an array aggregate directly in your if statement, like this:
if (new[] {1,2,3,4,5,6}.Contains(id)) {
}
Note: you need to add using System.Linq in order for this to compile.
Try this:
var numbers = new List<int>() {1,2,3,4,5,6};
if (numbers.Contains(myId))
{
}
int[] intArray = { 1, 2, 3, 4, 5 };
if (intArray.Contains(3))
// ...
using the Contains Extension method you can achieve this eaisly:
var myNumberList = new List<int>(){1,2,3,4};
// check using the Contains extension method
if(myNumberList.contains(TARGET_NUMBER))
{
// do your stuff here
}
from the official MSDN article:
Determines whether a sequence contains a specified element by using
the default equality comparer.
Link: http://msdn.microsoft.com/en-us/library/bb352880.aspx
Alternatively to List<T>.Contains, if you want to do this to keep a track of values you have already entered, you could use HashSet<int> as the Add methods returns true if the value is added:
var numbers = new HashSet<int>();
if (numbers.Add(myNumber))
{
// myNumber has just been inserted into numbers
}
The HashSet also has the added benefit of being designed to quickly find specific values inside it based on hash, and with int, the hash is simply the int itself.
And it has Contains:
if (numbers.Contains(myNumber))
{}
IEnumerable also has a Contains extension method for anything else:
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains(v=vs.110).aspx

Performing function on each array element, returning results to new array

I'm a complete Linq newbie here, so forgive me for a probably quite simple question.
I want to perform an operation on every element in an array, and return the result of each of these operations to a new array.
For example, say I have an array or numbers and a function ToWords() that converts the numbers to their word equivalents, I want to be able to pass in the numbers array, perform the ToWords() operation on each element, and pass out a string[]
I know it's entirely possible in a slightly more verbose way, but in my Linq adventures I'm wondering if it's doable in a nice one-liner.
You can use Select() to transform one sequence into another one, and ToArray() to create an array from the result:
int[] numbers = { 1, 2, 3 };
string[] strings = numbers.Select(x => ToWords(x)).ToArray();
It's pretty straight forward. Just use the Select method:
var results = array.Select(ToWords).ToArray();
Note that unless you need an array you don't have to call ToArray. Most of the time you can use lazy evaluation on an IEnumerable<string> just as easily.
There are two different approaches - you can use Select extension method or you can use select clause:
var numbers = new List<int>();
var strings1 = from num in numbers select ToWords(num);
var strings2 = numbers.Select(ToWords);
both of them will return IEnumerable<>, which you can cast as you need (for example, with .ToArray() or .ToList()).
You could do something like this :
public static string[] ProcessStrings(int[] intList)
{
return Array.ConvertAll<int, string>(intList, new Converter<int, string>(
delegate(int number)
{
return ToWords();
}));
}
If it is a list then :
public static List<string> ProcessStrings(List<int> intList)
{
return intList.ConvertAll<string>(new Converter<int, string>(
delegate(int number)
{
return ToWords();
}));
}
Straight simple:
string[] wordsArray = array.ToList().ConvertAll(n => ToWords(n)).ToArray();
If you are OK with Lists, rather than arrays, you can skip ToList() and ToArray().
Lists are much more flexible than arrays, I see no reason on earth not to use them, except for specific cases.

Adding to an Array

I have an array:
String[] ay = {
"blah",
"blah number 2"
"etc" };
... But now I want to add to this array at a later time, but I see no option to do so. How can this be done? I keep getting a message saying that the String cannot be converted to String[].
Thank you
Use a List rather than an array:
List<string> list = new List<string>();
list.Add( "blah" ) ;
Then, later, if you really do need it as an array:
string[] ay = list.ToArray();
Arrays are of fixed size, so after it has been created, you can't change the size of it (without creating a new array object)
Use the List<string> instead of the array.
Arrays can't change their size after they are declared. Use collections instead. For example: List.
As everyone's already said, use List in the System.Collections.Generic namespace.
You could also use a Hashtable which will allow you to give each string a meaning, or "key" which gives you an easy way to pull out a certain string with a keyword. (as for keeping messages stored in memory space for whatever purpose.)
You could also Create a new array each time you add a value, make the new array 1 bigger than the old one, copy all the data from the first array into the 2nd array, and then add your new value in the last slot (Length - 1)
Then replace the old array with your new one.
It's the most manual way of doing it.
But List and Hashtable work perfectly well too.
If you don't need indexing a specific array element (usage of brackets), but you want to be able to efficiently add or remove elements, you could use LinkedList.
If you do need indexing
have a look at Dictionary data type also in the System.Collection
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
so you could do something like
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "afljsd");
You can do this but I don't recommend it:
// Reallocates an array with a new size, and copies the contents
// of the old array to the new array.
// Arguments:
// oldArray the old array, to be reallocated.
// newSize the new array size.
// Returns A new array with the same contents.
public static System.Array ResizeArray (System.Array oldArray, int newSize) {
int oldSize = oldArray.Length;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType,newSize);
int preserveLength = System.Math.Min(oldSize,newSize);
if (preserveLength > 0)
System.Array.Copy (oldArray,newArray,preserveLength);
return newArray;
}
Here's an extension method to add the to arrays together and create a new string array
public static class StringArrayExtension
{
public static string[] GetStringArray (this string[] currentArray, string[] arrayToAdd)
{
List<String> list = new List<String>(currentArray);
list.AddRange(arrayToAdd);
return list.ToArray();
}
}

Categories