RSSAll Entries Tagged With: "arrays"

Use orderby to retrieve the values in an int array in ascending order in LINQ

using System;
using System.Linq;
class OrderbyDemo {
static void Main() {
int[] nums = { 10, -19, 4, 7, 2, -5, 0 };
// Create a query that obtains the values in sorted order.
[...]

Example of using IEnumerable on an integer array

// create an integer array
int[] myArray = new int[] {1, 2, 3, 4, 5 };
IEnumerable<int> intArray = myArray.Select(i => i);
//LINQ query expression
var query = from num in intArray
where num >= 3
select num;
foreach (var intResult in query)
{
Console.WriteLine(intResult);
}

Obtaining an Array from an ArrayList in C#

To obtain an actual array that contains the contents of the list we call the ToArray() method on the arraylist.

/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill
*/
using System;
using System.Collections;
class ArrayListToArray {
static void Main() {
ArrayList al = new ArrayList();
[...]

Example a two-dimensional array in C#

using System;
 
class TwoD {
public static void Main() {
int t, i;
int[,] table = new int[3, 4];
 
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
table[t,i] = (t*4)+i+1;
[...]

Compute the average of a set of values from an array

using System;
 
class Average {
public static void Main() {
int[] nums = new int[10];
int avg = 0;
 
nums[0] = 99;
nums[1] = 10;
nums[2] = 100;
nums[3] = 18;
nums[4] = 78;
[...]

One-dimensional array code sample

using System;
 
class ArrayDemo {
public static void Main() {
int[] sample = new int[10];
int i;
 
for(i = 0; i < 10; i = i+1)
sample[i] = i;
 
for(i = 0; i < 10; i = i+1)
[...]

Actionscript arrays

var myArray:Array = new Array();
myArray.push(1);
trace(myArray)
// 1 appears in the Output panel
myArray.push(2);
// the array now has two items: 1, 2
trace(myArray.pop());
// the pop() method removes the last item, displaying its value of 2
trace(myArray)
// the lone remaining item in the array, 1, is displayed

Dynamically adjust the size of an array in c#

Generally, after we create an array we cannot make any adjustment of its length, but the array class provides a static method named CreateInstance to create a dynamic array, of course, we can use this to dynamically adjust its features like the array length.

namespace ArrayManipulation
{
Class Program
{
[...]

Convert a bool to a byte array and display

Example to convert a bool to a byte array and display:

byte[] b = null;
b = BitConverter.GetBytes(true);
Console.WriteLine(BitConverter.ToString(b));

Convert a decimal to a byte array in c#

The following code shows how to convert a decimal to a byte array using a MemoryStream and a BinaryWriter.

// Create a byte array from a decimal
public static byte[] DecimalToByteArray (decimal src) {
 
// Create a MemoryStream as a buffer to hold the binary data
using (MemoryStream stream = new [...]