using …

Pure C#

‘Array’ Kategorisi için Arşiv

How To Merge Two Arrays in ASP.NET?

Yazan: esersahin 12/02/2009

http://codehighstreet.com/Snippets/how_to_merge_two_arrays.aspx

With Duplicates

private string[] MergeArray(string[] DestinationArray, string[] SourceArray)

{

int iSourceIndex;

int iDestinationLength = DestinationArray.Length;

if (SourceArray.Length > 0)

Array.Resize(ref DestinationArray, DestinationArray.Length + SourceArray.Length);

for (iSourceIndex = 0; iSourceIndex < SourceArray.Length ; iSourceIndex++)

{

DestinationArray[iDestinationLength + iSourceIndex] = SourceArray[iSourceIndex];

}

return DestinationArray;

}

Without Duplicates

private string[] MergeArray(string[] DestinationArray, string[] SourceArray)

{

int iSourceIndex;

int iDestinationLength = DestinationArray.Length;

if (SourceArray.Length > 0)

Array.Resize(ref DestinationArray, DestinationArray.Length + SourceArray.Length);

for (iSourceIndex = 0; iSourceIndex < SourceArray.Length ; iSourceIndex++)

{

if (Array.IndexOf(arrDestination, arrSource[iSourceLength]) == -1)

DestinationArray[iDestinationLength + iSourceIndex] = SourceArray[iSourceIndex];

}

return DestinationArray;

}

}

Array.IndexOf will do a search for the specified object on array and returns the index of the first occurrence. it will return -1 if it is not find anything on the array

Yazı kategorisi: Array | » yorum bırak;

Passing an array of values to SQL Server (Stored Procedure) without parsing/string manipulation

Yazan: esersahin 24/11/2008

http://sqlblogcasts.com/blogs/tonyrogerson/archive/2007/03/18/passing-an-array-of-values-to-sql-server-stored-procedure-without-parsing-string-manipulation.aspx

If you are splitting a CSV that just contains numbers, for instance surrogate key id’s that you are passing in because of a multiple select checkbox or something and you know the values range then why split the string? It’s simpler than that – no splitting required, just use dynamic SQL and an IN coupled with a numbers table…

Create the numbers table, note – if you are just passing in the surrogate key id of say your individual table then you don’t even need a numbers table – just use the id column on the individual table…

create table numbers (

      number      int    not null primary key clustered

 

)

 

declare @i int

 

set @i = 1

 

while @i <= 32767

begin

      insert numbers ( number ) values( @i )

      set @i = @i + 1

 

end

go

 

create proc csv_to_set

      @csv varchar(max)

as

begin

      set @csv = replace( @csv, ””, ””” )

 

      if object_id( ‘tempdb..#csvset’ ) is null

      begin

            print ‘#csvset must already exist before this proc is called’

          create table #csvset (

                csv_value smallint not null

                )

      end

      else

      begin

            insert #csvset ( csv_value )

                  exec(

                              select number

                              from numbers

                              where number in ( ‘ + @csv + ‘ )

                              )

 

            if @@rowcount <> ( LEN( @csv + ‘,’ ) - LEN( REPLACE( @csv + ‘,’, ‘,’, ) ) )

            begin

                  print cast( ( LEN( @csv + ‘,’ ) - LEN( REPLACE( @csv + ‘,’, ‘,’, ) ) ) as varchar(50) )

 

                  raiserror( ‘A value exists in the CSV that is not in the numbers table’, 16, 1 )

                  truncate table #csvset

 

                  return

 

            end

 

      end

end

 

The procedure is run using the example below, unfortunately because you can’t put dynamic SQL in a function then you can only do this in a stored procedure (a table valued function would remove the need for the # table).

I’ve also put a check in there that compares the @@ROWCOUNT (inserted rows) against how many values are in the CSV, if there is a mismatch then an error is thrown, but by doing this check you also prevent duplicate values being entered on the @csv, basically the IN clause does an implicit SELECT DISTINCT on your @csv removing the duplicate values – this is a bad thing if you are entering data and can have duplicates but it’s a good thing if you just want the unique values.

    Create results table

create table #csvset (

      csv_value   smallint not null

      )

 

    Split the string up

exec csv_to_set ‘55, 99, 1212′

 

    Results

select *

from #csvset

 

drop table #csvset

Filed under:

Yazı kategorisi: Array, SQL, Sql Server, Stored Procedure | » yorum bırak;

List<(Of )>)..::.ToArray Method

Yazan: esersahin 08/11/2008

http://msdn.microsoft.com/en-us/library/x303t819.aspx

Copies the elements of the List<(Of <(T>)>) to a new array.

Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)

Visual Basic (Declaration)
Public Function ToArray As T()
Visual Basic (Usage)
Dim instance As List
Dim returnValue As T()

returnValue = instance.ToArray()
C#
public T[] ToArray()
Visual C++
public:
array<T>^ ToArray()
JScript
public function ToArray() : T[]

Return Value

Type: array<T>[]()[]
An array containing copies of the elements of the List<(Of <(T>)>).

The elements are copied using Array..::.Copy, which is an O(n) operation, where n is Count.

This method is an O(n) operation, where n is Count.

The following code example demonstrates the ToArray method and other methods of the List<(Of <(T>)>) class that act on ranges. At the end of the code example, the GetRange method is used to get three items from the list, beginning with index location 2. The ToArray method is called on the resulting List<(Of <(T>)>), creating an array of three elements. The elements of the array are displayed.

Visual Basic
Imports System
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim input() As String = { "Brachiosaurus", _
                                  "Amargasaurus", _
                                  "Mamenchisaurus" }

        Dim dinosaurs As New List(Of String)(input)

        Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "AddRange(dinosaurs)")
        dinosaurs.AddRange(dinosaurs)

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "RemoveRange(2, 2)")
        dinosaurs.RemoveRange(2, 2)

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        input = New String() { "Tyrannosaurus", _
                               "Deinonychus", _
                               "Velociraptor" }

        Console.WriteLine(vbLf & "InsertRange(3, input)")
        dinosaurs.InsertRange(3, input)

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "output = dinosaurs.GetRange(2, 3).ToArray")
        Dim output() As String = dinosaurs.GetRange(2, 3).ToArray()

        Console.WriteLine()
        For Each dinosaur As String In output
            Console.WriteLine(dinosaur)
        Next

    End Sub
End Class

' This code example produces the following output:
'
'Capacity: 3
'
'Brachiosaurus
'Amargasaurus
'Mamenchisaurus
'
'AddRange(dinosaurs)
'
'Brachiosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Amargasaurus
'Mamenchisaurus
'
'RemoveRange(2, 2)
'
'Brachiosaurus
'Amargasaurus
'Amargasaurus
'Mamenchisaurus
'
'InsertRange(3, input)
'
'Brachiosaurus
'Amargasaurus
'Amargasaurus
'Tyrannosaurus
'Deinonychus
'Velociraptor
'Mamenchisaurus
'
'output = dinosaurs.GetRange(2, 3).ToArray
'
'Amargasaurus
'Tyrannosaurus
'Deinonychus
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] input = { "Brachiosaurus",
                           "Amargasaurus",
                           "Mamenchisaurus" };

        List<string> dinosaurs = new List<string>(input);

        Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nAddRange(dinosaurs)");
        dinosaurs.AddRange(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nRemoveRange(2, 2)");
        dinosaurs.RemoveRange(2, 2);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        input = new string[] { "Tyrannosaurus",
                               "Deinonychus",
                               "Velociraptor"};

        Console.WriteLine("\nInsertRange(3, input)");
        dinosaurs.InsertRange(3, input);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\noutput = dinosaurs.GetRange(2, 3).ToArray()");
        string[] output = dinosaurs.GetRange(2, 3).ToArray();

        Console.WriteLine();
        foreach( string dinosaur in output )
        {
            Console.WriteLine(dinosaur);
        }
    }
}

/* This code example produces the following output:

Capacity: 3

Brachiosaurus
Amargasaurus
Mamenchisaurus

AddRange(dinosaurs)

Brachiosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Amargasaurus
Mamenchisaurus

RemoveRange(2, 2)

Brachiosaurus
Amargasaurus
Amargasaurus
Mamenchisaurus

InsertRange(3, input)

Brachiosaurus
Amargasaurus
Amargasaurus
Tyrannosaurus
Deinonychus
Velociraptor
Mamenchisaurus

output = dinosaurs.GetRange(2, 3).ToArray()

Amargasaurus
Tyrannosaurus
Deinonychus
 */
Visual C++
using namespace System;
using namespace System::Collections::Generic;

void main()
{
    array<String^>^ input = { "Brachiosaurus",
                              "Amargasaurus",
                              "Mamenchisaurus" };

    List<String^>^ dinosaurs =
        gcnew List<String^>((IEnumerable<String^>^) input);

    Console::WriteLine("\nCapacity: {0}", dinosaurs->Capacity);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nAddRange(dinosaurs)");
    dinosaurs->AddRange(dinosaurs);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nRemoveRange(2, 2)");
    dinosaurs->RemoveRange(2, 2);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    input = gcnew array<String^> { "Tyrannosaurus",
                                   "Deinonychus",
                                   "Velociraptor"};

    Console::WriteLine("\nInsertRange(3, (IEnumerable<String^>^) input)");
    dinosaurs->InsertRange(3, (IEnumerable<String^>^) input);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\noutput = dinosaurs->GetRange(2, 3)->ToArray()");
    array<String^>^ output = dinosaurs->GetRange(2, 3)->ToArray();

    Console::WriteLine();
    for each(String^ dinosaur in output )
    {
        Console::WriteLine(dinosaur);
    }
}

/* This code example produces the following output:

Capacity: 3

Brachiosaurus
Amargasaurus
Mamenchisaurus

AddRange(dinosaurs)

Brachiosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Amargasaurus
Mamenchisaurus

RemoveRange(2, 2)

Brachiosaurus
Amargasaurus
Amargasaurus
Mamenchisaurus

InsertRange(3, (IEnumerable<String^>^) input)

Brachiosaurus
Amargasaurus
Amargasaurus
Tyrannosaurus
Deinonychus
Velociraptor
Mamenchisaurus

output = dinosaurs->GetRange(2, 3)->ToArray()

Amargasaurus
Tyrannosaurus
Deinonychus
 */
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 2.0, 1.0

Yazı kategorisi: Array, Generic, List | » yorum bırak;

Converting an Array to a Collection

Yazan: esersahin 08/11/2008

http://www.exampledepot.com/egs/java.util/coll_Array2Col.html?l=rel

// Fixed-size list
    List list = Arrays.asList(array);

    // Growable list
    list = new LinkedList(Arrays.asList(array));

    // Duplicate elements are discarded
    Set set = new HashSet(Arrays.asList(array));

Yazı kategorisi: Array, Java | » yorum bırak;

Comparing Arrays

Yazan: esersahin 08/11/2008

http://www.exampledepot.com/egs/java.util/coll_CompArray.html?l=rel

// null arrays are equal
    boolean[] bArr1 = null;
    boolean[] bArr2 = null;
    boolean b = Arrays.equals(bArr1, bArr2);                   // true

    // Compare two boolean arrays
    bArr1 = new boolean[]{true, false};
    bArr2 = new boolean[]{true, false};
    b = Arrays.equals(bArr1, null);                            // false
    b = Arrays.equals(bArr1, bArr2);                           // true

    // There are equals() methods for all eight primitive types
    b = Arrays.equals(new byte[]{0}, new byte[]{0});           // true
    b = Arrays.equals(new char[]{'a'}, new char[]{'a'});       // true
    b = Arrays.equals(new short[]{0}, new short[]{0});         // true
    b = Arrays.equals(new int[]{0}, new int[]{0});             // true
    b = Arrays.equals(new long[]{0L}, new long[]{0L});         // true
    b = Arrays.equals(new float[]{0F}, new float[]{0F});       // true
    b = Arrays.equals(new double[]{0D}, new double[]{0D});     // true

    // When comparing Object arrays, null elements are equal.
    // If the elements are not null, Object.equals() is used.
    b = Arrays.equals(new String[]{"a"}, new String[]{"a"});   // true
    b = Arrays.equals(new String[]{null}, new String[]{null}); // true
    b = Arrays.equals(new String[]{"a"}, new String[]{null});  // false

Yazı kategorisi: Array, Java | » yorum bırak;

Filling Elements in an Array

Yazan: esersahin 08/11/2008

http://www.exampledepot.com/egs/java.util/coll_FillArray.html?l=rel

The Arrays class has conveninent methods for filling arrays of all eight primitive types:

    boolean[] booleanArr = new boolean[10];
    boolean booleanFillValue = false;
    Arrays.fill(booleanArr, booleanFillValue);

    byte[] byteArr = new byte[10];
    byte byteFillValue = (byte)0xFF;
    Arrays.fill(byteArr, byteFillValue);

    char[] charArr = new char[10];
    char charFillValue = 0xFF;
    Arrays.fill(charArr, charFillValue);

    short[] shortArr = new short[10];
    short shortFillValue = 0xFF;
    Arrays.fill(shortArr, shortFillValue);

    int[] intArr = new int[10];
    int intFillValue = -1;
    Arrays.fill(intArr, intFillValue);

    long[] longArr = new long[10];
    long longFillValue = -1;
    Arrays.fill(longArr, longFillValue);

    float[] floatArr = new float[10];
    float floatFillValue = -1;
    Arrays.fill(floatArr, floatFillValue);

    double[] doubleArr = new double[10];
    double doubleFillValue = -1;
    Arrays.fill(doubleArr, doubleFillValue);

There is also a method for filling object arrays:

    String[] StringArr = new String[1];
    String StringFillValue = "";
    Arrays.fill(StringArr, StringFillValue);

By default, the nine fill methods shown above set all the elements in the array with the fill value. Each fill method has an overloaded version that can restrict the fill to a contiguous range of elements:

    // Fill elements 0, 1, 2, and 3; the end index is exclusive
    int startIndex = 0;
    int endIndex = 4;

    Arrays.fill(booleanArr, startIndex, endIndex, booleanFillValue);
    Arrays.fill(byteArr, startIndex, endIndex, byteFillValue);
    Arrays.fill(charArr, startIndex, endIndex, charFillValue);
    Arrays.fill(shortArr, startIndex, endIndex, shortFillValue);
    Arrays.fill(intArr, startIndex, endIndex, intFillValue);
    Arrays.fill(longArr, startIndex, endIndex, longFillValue);
    Arrays.fill(floatArr, startIndex, endIndex, floatFillValue);
    Arrays.fill(doubleArr, startIndex, endIndex, doubleFillValue);
    Arrays.fill(StringArr, startIndex, endIndex, StringFillValue);

Yazı kategorisi: Array, Java | » yorum bırak;

Converting a Collection to an Array from The Java Developers Almanac 1.4

Yazan: esersahin 08/11/2008

http://www.exampledepot.com/egs/java.util/coll_GetArrayFromVector.html

// Create an array containing the elements in a list
    Object[] objectArray = list.toArray();
    MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

    // Create an array containing the elements in a set
    objectArray = set.toArray();
    array = (MyClass[])set.toArray(new MyClass[set.size()]);

    // Create an array containing the keys in a map
    objectArray = map.keySet().toArray();
    array = (MyClass[])map.keySet().toArray(new MyClass[set.size()]);

    // Create an array containing the values in a map
    objectArray = map.values().toArray();
    array = (MyClass[])map.values().toArray(new MyClass[set.size()]);

Yazı kategorisi: Array, Java | » yorum bırak;