Posts

Showing posts with the label C#

Reverse array in C#

To reverse an array we can use Reverse method of Array class. Overloads This method has two overloads. First overload takes an array as parameter which will be reversed. Second overload takes 3 parameters. First is array second is start index from where to start and third is length. string []arr = new string [3]; arr[0] = "One" ; arr[1] = "Two" ; arr[2] = "Three" ; Console .WriteLine( "Array before reversing" ); foreach ( string str in arr) {     Console .WriteLine(str); } Array .Reverse(arr); Console .WriteLine( "Array after reversing" ); foreach ( string str in arr) {     Console .WriteLine(str); } Output Array before reversing One Two Three Array after reversing Three Two One             

Using string array in C#

To create a stirng array we can define array of string type and length of array. string []arr = new string [5]; We can assign value to array by using index of array. Similarly we can get value by using index of array. Assigning value to array arr[0] = "One" ; arr[1] = "Two" ; arr[2] = "Three" ; arr[3] = "Four" ; arr[4] = "Five" ; Getting value from array string val = arr[2];

Get character array from string in C#

To get a  char  array from string we use ToCharArray method. Overloads This method has one overload which takes two parameters. First is StartIndex and second is Length. Return Type Return type of this method is  char  array. string str = "I like rain" ; char [] arr = str.ToCharArray(); foreach ( char c in arr) {   Console .WriteLine(c); }

Inserting a string within string using C#

To insert a string within a string we use Insert method . This method takes two parameters. First is start index where we want to insert. Second parameter is value which we want to insert. Return type of this method is string. Here we will insert a string at 0 index . Output is shown before and after inserting the string. string str = "like rain" ; Console .WriteLine(str); str = str.Insert(0, "I " ); Console .WriteLine(str); Output Like rain I like rain

Convert string to upper case and lower case

To convert a string to upper case we use ToUpper method. Return type of this method is string. To convert a string into lower case we use ToLower method. Return type of this method is string. string str = "i like rain" ; str = str.ToUpper(); Console .WriteLine(str); str = str.ToLower(); Console .WriteLine(str); Output I LIKE RAIN I like rain

Get length of a string in C#

To get length of a string we use Length property of string . This returns an integer value indicating how many characters a string contains. string str = "I like rain" ; int length = str.Length; Console .WriteLine( "Length of str is " + length); Output Length of str is 11

Remove extra spaces from string in C#

Strings are commonly used in C#. Sometimes string can contain unwanted spaces in beginning or at end. To remove such spaces we use Trim method. This method removes extra spaces from start and end of string. Return type of this method is string. string Fruit = "  Apple  " ; Fruit = Fruit.Trim(); Console .WriteLine(Fruit); Output Apple

To check if string ends with specific word(s)

To check if a string ends with specific word(s) we use EndsWith method. Return type of this method is Boolean. string Fruit = "Apple" ; if (Fruit.EndsWith( "e" , StringComparison .OrdinalIgnoreCase)) {     Console .WriteLine( "Fruit ends with e" ); } Output Fruit ends with e

To check if string starts with specific word

To check if a string starts with some specific word(s) we use StartsWith method. Return type of this method is Boolean. string Fruit = "Apple" ; if (Fruit.StartsWith( "A" )) {     Console .WriteLine( "Fruit starts with A" ); } Output Fruit starts with A

Split string into multiple strings in C#

To split a string into multiple strings we use Split method. This method has 6 overloads. We will use the Character separator overload to split string using single character. Split method returns array of strings. string StrToSplit = "Sunday is funday" ; string [] SplittedString = StrToSplit.Split( ' ' ); foreach ( string str in SplittedString) {     Console .WriteLine(str); } Output Sunday Is funday

How to check if string is null or empty

To check if string is null or empty we use IsNullOrEmpty method.This method returns Boolean value. If string is null or is empty it will return true otherwise false . string Name = "" ; if ( string .IsNullOrEmpty(Name)) {     Console .WriteLine( "Name is null or empty" ); } Output Name is null or empty

Remove string from string in C#

To remove a string from string we use Remove method. Return type of this method is string. This method has two overloads . First overload accepts start index. All String next to start index will be removed. Second overload accepts start index and number of characters to remove. string Fruit = "Orange" ; Fruit = Fruit.Remove(3); Console .WriteLine(Fruit); OutPut Ora string Fruit = "Orange" ; Fruit = Fruit.Remove(0,3); Console .WriteLine(Fruit); Output nge

Replace character/string in C#

To replace a character or string from a string we use Replace method. This method has two overloads. First accepts a character which is to be replaced and new character to replace old character. Second accepts string which is to be replaced and new string to replace old string. string Fruit = "Orange" ; Fruit = Fruit.Replace( 'e' , 'E' ); Fruit = Fruit.Replace( "an" , "AN" ); Console .WriteLine(Fruit); Output OrANgE

Get substring from a string in C#

To get substring from a string in C# we use Substring method. This method has two overloads. First takes starting index from where to start extracting substring. Seconds takes start index and length of string to extract. string Fruit = "Orange" ; string Substr = Fruit.Substring(2);     //Starts getting substring from Index 2 string Substr1 = Fruit.Substring(2, 2); //Starts getting substring from Index 2 and gets only two characters Console .WriteLine(Substr); Console .WriteLine(Substr1); Output “ange” “an”

Check existence of one string in another string in C#

If we want to check whether a string contains a specific string or character we can use .Contains method. We can also use IndexOf method to check existence of a string in another string . string str1 = "Orange" ; if (str1.Contains( "an" )) {   Console .WriteLine( "str1 contains an" ); } Using IndexOf method if (str1.IndexOf( "an" ) > -1) {   Console .WriteLine( "str1 contains an" ); }

Compare two strings equality in C#

We can simply compare two strings using == operator. But there is a better way to compare strings using Equals method. Also we can ignore case to make comparison more accurate. string str1 = "OraNge" ; string str2 = "orange" ; if (str1.Equals(str2, StringComparison .OrdinalIgnoreCase)) {     Console .WriteLine( "Both strings are equal" ); }

Reading / looping through datatable C#

DataTable dt = new DataTable (); dt.Columns.Add( "ID" ); dt.Columns.Add( "Name" ); dt.Columns.Add( "Address" ); DataRow dr = dt.NewRow(); dr[ "ID" ] = 1; dr[ "Name" ] = "John" ; dr[ "Address" ] = "Street 10" ; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr[ "ID" ] = 2; dr[ "Name" ] = "Smith" ; dr[ "Address" ] = "Street 10" ; dt.Rows.Add(dr1); //Looping through datatable foreach ( DataRow row in dt.Rows) {     Console .WriteLine(row[ "ID" ]);     Console .WriteLine(row[ "Name" ]);     Console .WriteLine(row[ "Address" ]); }

Read ConnnectionString from web.config in C#

ConnectionString is normally stored in web.config and it is recommended to store connectionstring in web.config file. To use connectionstring in our application we need to read connectionstring from web.config. We need to use ConfigurationManager class in order to read connectionstring from web.config . You may need to add reference for assembly “ System.Configuration ” before using ConfigurationManager class. string ConnectionString = ConfigurationManager .ConnectionStrings[ "DefaultConnection" ].ConnectionString; SqlConnection con = new SqlConnection (ConnectionString) ; Web.Config < connectionStrings >     < add name = " DefaultConnection " providerName = " System.Data.SqlClient " connectionString = " YourConnectionStringHere " /> </ connectionStrings >

How to call Stored Procedure using C#

Stored Procedures are used to execute a specific set of commands. To use stored procedure in .Net we can use SqlCommand object.  There are properties of SqlCommand which we need to set in order to call stored procedure. First we need to set CommandText property we will assign this property with name of our stored procedure. Then we need to tell CommandType of SqlCommand which will be CommandType .StoredProcedure in case of stored procedure, in case of simple query we will set this to CommandType .Text DataTable dt = new DataTable (); using ( SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "DefaultConnection" ].ConnectionString)) {    using ( SqlCommand cmd = new SqlCommand ())    {       using ( SqlDataAdapter adapter = new SqlDataAdapter ())       {          con.Open();          cmd.Command...

Load data from SqlDataReader into DataTable

SqlDatareader is used in .Net to read data from sql server database. We may have a situation where we need to fill data into DataTable from SqlDataReader . DatatTable has a Load method which accepts SqlDataReader object and fills DataTable with data. DataTable dt = new DataTable (); using ( SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "DefaultConnection" ].ConnectionString)) {    using ( SqlCommand cmd = new SqlCommand ())    {       con.Open();       cmd.CommandText = "Select * from tblUsers" ;       cmd.Connection = con;       cmd.CommandType = CommandType .Text;        SqlDataReader reader = null ;       reader = cmd.ExecuteReader();       dt.Load(reader);                ...