Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Wednesday, June 16, 2010

DataTable To String Array in C# without using a for Loop

Many time we need need to get data from dataset\Datatable to array to pass it to some function or third API like x axis or y axis series of chart controls or to some other reporting or data binding control may be dropdown. it becomes difficult to get the data of a column(s) in array and finally we end up writing a for loop. here is a sample example by which we can simply get array of a column(s) with out a for loop
public static string DataRowToString(DataRow dr)
{
       return dr["columns"].ToString();
}
public string [] DataTableToArray(DataTable dt)
{
     DataRow[] dr = dt.Select();
     string [] strArr= Array.ConvertAll(dr, new Converter(DataRowToString));
     return strArr;
}

Array.ConvertAll() function simply converts the array of one to another so here in above example we are passing dr as an araay of datarows in first arguments. second argument is a Converter delegate type which convert one type to another so in this we will pass a link to delegate which is DataRowToString() function ,the delegate should know the input datatype and output datatype which is datatrow and string in this case respectively. function DataRowToString noe simply takes a datarow and return the string value for the column specified. which can be extended for multiple columns also.

Ref: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/46ef6ca8-7f66-489a-a0f6-b6b7c4200d16

Friday, December 5, 2008

Arrays in C# : Value type or Ref type

Array Class is the abstract class provides methods for manipulation of array....
int [] intArray;
intArray = new int[5]

string [] names;
names = new string[10];

now from above which one is value type and which one is refrence type (Int is value type and String is refrence type)
 
ok the topic is interesting lets's play with it
 
 
as we all know the difference in readonly and const keyword in C#
readonly can be applied with only ref type and const can be only with value type except string
 
and if you try to make the above said array to const it will show error while it will work fine with readonly
try using this line of code in your program
 
you may also try this see the error
public const int[] intArray = new int[5];

now lets do another test on these arrays
declare one readonly array and try to change it svalue

like readonly int [] intarray = {1,2,3}

intArray[1] = 4

it will execute fine

because array is ref type so ref remains same when readonly but value can be changed
 
 
so we can finally conclude that all array are refernce type whether it contains value type or reference type