DataTable.Load(IDataReader);
Convert Data Reader to Data Table
DataTable.Load(IDataReader);
Convert data table to data reader
dt = getDataFromDB();
DataTableReader dtr;
dtr = dt.CreateDataReader();
while (dtr.Read())
{
//Do your tasks
}
30 Common String Operations in C# and VB.NET
In this article, I have compiled some common String operations that we encounter while working with the String class. All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
1. Iterate a String – You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop gives you more flexibility over the iteration.
C#
for (int i = 0; i < strOriginal.Length; i++)
{
MessageBox.Show(strOriginal[i].ToString());
}
or
foreach (char c in strOriginal)
{
MessageBox.Show(c.ToString());
}
For i As Integer = 0 To strOriginal.Length - 1
MessageBox.Show(strOriginal(i).ToString())
Next i
Or
For Each c As Char In strOriginal
MessageBox.Show(c.ToString())
Next c
2. Split a String – You can split strings using String.Split(). The method takes an array of chars, representing characters to be used as delimiters. In this example, we will be splitting the strOriginal string using ‘space’ as delimiter.
C#
char[] delim = {' '};
string[] strArr = strOriginal.Split(delim);
foreach (string s in strArr)
{
MessageBox.Show(s);
}
Dim delim As Char() = {" "c}
Dim strArr As String() = strOriginal.Split(delim)
For Each s As String In strArr
MessageBox.Show(s)
Next s
3. Extract SubStrings from a String – The String.Substring() retrieves a substring from a string starting from a specified character position. You can also specify the length.
C#
// only starting position specified
strModified = strOriginal.Substring(25);
MessageBox.Show(strModified);
// starting position and length of string to be extracted specified
strModified = strOriginal.Substring(20, 3);
MessageBox.Show(strModified);
' only starting position specified
strModified = strOriginal.Substring(25)
MessageBox.Show(strModified)
' starting position and length of string to be extracted specified
strModified = strOriginal.Substring(20, 3)
MessageBox.Show(strModified)
4. Create a String array – There are different ways to create a Single Dimensional and Multi Dimensional String arrays. Let us explore some of them:
C#
// Single Dimensional String Array
string[] strArr = new string[3] { "string 1", "string 2", "string 3"};
// Omit Size of Array
string[] strArr1 = new string[] { "string 1", "string 2", "string 3" };
// Omit new keyword
string[] strArr2 = {"string 1", "string 2", "string 3"};
// Multi Dimensional String Array
string[,] strArr3 = new string[2, 2] { { "string 1", "string 2" }, { "string 3", "string 4" } };
// Omit Size of Array
string[,] strArr4 = new string[,] { { "string 1", "string 2" }, { "string 3", "string 4" } };
// Omit new keyword
string[,] strArr5 = { { "string 1", "string 2" }, { "string 3", "string 4" } };
' Single Dimensional String Array
Dim strArr As String() = New String(2) { "string 1", "string 2", "string 3"}
' Omit Size of Array
Dim strArr1 As String() = New String() { "string 1", "string 2", "string 3" }
' Omit new keyword
Dim strArr2 As String() = {"string 1", "string 2", "string 3"}
' Multi Dimensional String Array
Dim strArr3 As String(,) = New String(1, 1) { { "string 1", "string 2" }, { "string 3", "string 4" } }
' Omit Size of Array
Dim strArr4 As String(,) = New String(, ) { { "string 1", "string 2" }, { "string 3", "string 4" } }
' Omit new keyword
Dim strArr5 As String(,) = { { "string 1", "string 2" }, { "string 3", "string 4" } }
5. Reverse a String – One of the simplest ways to reverse a string is to use the StrReverse() function. To use it in C#, you need to add a reference to the Microsoft.VisualBasic dll.
C#
string strModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
MessageBox.Show(strModified);
Dim strModified As String = StrReverse(strOriginal)
MsgBox(strModified)
6. Compare Two Strings – You can use the String.Compare() to compare two strings. The third parameter is a Boolean parameter that determines if the search is case sensitive(false) or not(true).
C#
if ((string.Compare(strOriginal, strModified, false)) < 0)
{
MessageBox.Show("strOriginal is less than strOriginal1");
}
else if ((string.Compare(strOriginal, strModified, false)) > 0)
{
MessageBox.Show("strOriginal is more than strOriginal1");
}
else if ((string.Compare(strOriginal, strModified, false)) == 0)
{
MessageBox.Show("Both strings are equal");
}
If (String.Compare(strOriginal, strModified, False)) < 0 Then
MessageBox.Show("strOriginal is less than strOriginal1")
ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then
MessageBox.Show("strOriginal is more than strOriginal1")
ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then
MessageBox.Show("Both strings are equal")
End If
7. Convert a String to Byte[] (Byte Array) – The Encoding.GetBytes() encodes all the characters into a sequence of bytes. The method contains six overloads out of which we will be using the Encoding.GetBytes(String).
C#
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)
Note: You can adopt different character encoding schemes (ASCII, Unicode etc.) based on your requirement.
8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.
C#
// Assuming you have a Byte Array byte[] b
strModified = Encoding.Unicode.GetString(b);
' Assuming you have a Byte Array byte[] b
strModified = Encoding.Unicode.GetString(b)
ppppline
Use .NET Built-in Methods to Save Time and Headaches
During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.
In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.
Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.
Code Block #1 – Check string for nullity or emptiness
NOT Recommended
- str = "something"
- if (str == null || str == String.Empty)
- {
- // Oh no! the string isn't valid!
- }
str = "something" if (str == null || str == String.Empty) { // Oh no! the string isn't valid! }Recommended
- str = "something"
- if (String.IsNullOrEmpty(str))
- {
- // Oh no! the string isn't valid!
- }
str = "something" if (String.IsNullOrEmpty(str)) { // Oh no! the string isn't valid! }Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)
NOT Recommended
- str = "something"
- if (str == null || str.Trim() == String.Empty)
- {
- // Oh no! the string isn't valid!
- }
str = "something" if (str == null || str.Trim() == String.Empty) { // Oh no! the string isn't valid! }Recommended (C# 4.0 Only)
- str = "something"
- if (String.IsNullOrWhiteSpace(str))
- {
- // Oh no! the string isn't valid!
- }
str = "something" if (String.IsNullOrWhiteSpace(str)) { // Oh no! the string isn't valid! }Code Block #3 – Copy an Array
NOT Recommended
- string[] source = new string[] { "a", "b", "c" };
- string[] dest = new string[3];
- for (int i=0; i < source.Length; i++)
- {
- dest[i] = source[i];
- }
string[] source = new string[] { "a", "b", "c" }; string[] dest = new string[3]; for (int i=0; i < source.Length; i++) { dest[i] = source[i]; }Recommended
- string[] source = new string[] { "a", "b", "c" };
- string[] dest = new string[3];
- Array.Copy(surce, dest, source.Length);
string[] source = new string[] { "a", "b", "c" }; string[] dest = new string[3]; Array.Copy(surce, dest, source.Length);Code Block #4 – Check if a char is a digit
NOT Recommended
- char c = '1';
- if (c == '1' || c == '2' || c == '3' ||
- c == '4' || c == '5' || c == '6' ||
- c == '7' || c == '8' || c == '9' ||
- c == '0')
- {
- // It's a digit!
- }
char c = '1'; if (c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '0') { // It's a digit! }Recommended
- char c = '1';
- if (Char.IsDigit(c))
- {
- // It's a digit!
- }
char c = '1'; if (Char.IsDigit(c)) { // It's a digit! }Code Block #5 – Combine Paths
NOT Recommended
- string folder = @"C:\MyDir";
- string file = "MyFile.docx";
- // Combine to make a path
- string path = folder + @"\" + file;
string folder = @"C:\MyDir"; string file = "MyFile.docx"; // Combine to make a path string path = folder + @"\" + file;
Recommended
- string folder = @"C:\MyDir";
- string file = "MyFile.docx";
- // Combine
- string path = System.IO.Path.Combine(folder, file);
string folder = @"C:\MyDir"; string file = "MyFile.docx"; // Combine string path = System.IO.Path.Combine(folder, file);
Code Block #6 – Get file extension out of a file path
NOT Recommended
- string path = @"C:\MyDir\MyFile.docx";
- string extension = path.Substring(path.LastIndexOf("."));
string path = @"C:\MyDir\MyFile.docx"; string extension = path.Substring(path.LastIndexOf("."));Recommended
- string path = @"C:\MyDir\MyFile.docx";
- string extension = System.IO.Path.GetExtension(path);
string path = @"C:\MyDir\MyFile.docx"; string extension = System.IO.Path.GetExtension(path);
Code Block #7 – Get MyDocuments Path
NOT Recommended
- // Probably some nasty stuff here
// Probably some nasty stuff here
Recommended
- Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Code Block #8 – Check if object is of a specific type
NOT Recommended
- object obj = "str";
- if (obj.GetType() == typeof(String))
- {
- // It's a string!
- }
object obj = "str"; if (obj.GetType() == typeof(String)) { // It's a string! }Recommended
- object obj = "str";
- if (obj is String)
- {
- // It's a string!
- }
object obj = "str"; if (obj is String) { // It's a string! }As Adrian Aisemberg has pointed out, these samples are not entirely the same. The is keyword will return true also if obj is of a derivative type of String (in this sample).
Code Block #9 – Set default enum value
NOT Recommended
- public class MyClass
- {
- private enum Sample
- {
- A,
- B,
- C
- }
- static Sample s = Sample.B; // Set default value explicitly
- public static void Run()
- {
- Console.WriteLine(s); // Prints B
- }
- }
public class MyClass { private enum Sample { A, B, C } static Sample s = Sample.B; // Set default value explicitly public static void Run() { Console.WriteLine(s); // Prints B } }Recommended
- public class MyClass
- {
- private enum Sample
- {
- A,
- B = 0, // Make B the default value
- C
- }
- static Sample s; // Default value will be used
- public static void Run()
- {
- Console.WriteLine(s); // Prints B
- }
- }
public class MyClass { private enum Sample { A, B = 0, // Make B the default value C } static Sample s; // Default value will be used public static void Run() { Console.WriteLine(s); // Prints B } }Code Block #10 – Check if a string starts with another string
NOT Recommended
- string str = "Hello World";
- if (str.Substring(0, 5) == "Hello")
- {
- // String starts with Hello!
- }
string str = "Hello World"; if (str.Substring(0, 5) == "Hello") { // String starts with Hello! }Recommended
- string str = "Hello World";
- if (str.StartsWith("Hello"))
- {
- // String starts with Hello!
- }
string str = "Hello World"; if (str.StartsWith("Hello")) { // String starts with Hello! }Code Block #11 – Convert list of items of one type to a list of items of a different type
NOT Recommended
- List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
- List<string> convertedList = new List<string>();
- foreach (int item in list)
- {
- convertedList.Add(item.ToString());
- }
List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 }); List<string> convertedList = new List<string>(); foreach (int item in list) { convertedList.Add(item.ToString()); }Recommended
- List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
- List<string> convertedList = list.ConvertAll<string>(Convert.ToString);
List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 }); List<string> convertedList = list.ConvertAll<string>(Convert.ToString);Code Block #12 – Check if a string contains a number and get the number
NOT Recommended
- string str = "4";
- int num = 0;
- bool success = false;
- try
- {
- num = Convert.ToInt32(str);
- success = true;
- }
- catch
- {
- success = false;
- }
- if (success)
- {
- // Do something with the number
- }
string str = "4"; int num = 0; bool success = false; try { num = Convert.ToInt32(str); success = true; } catch { success = false; } if (success) { // Do something with the number }Recommended
- string str = "4";
- int num = 0;
- if (Int32.TryParse(str, out num))
- {
- // Do something with the number
- }
string str = "4"; int num = 0; if (Int32.TryParse(str, out num)) { // Do something with the number }Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)
NOT Recommended
- const string str = "put me in a file";
- const string file = @"c:\logs\file.txt";
- var fs = new FileStream(file, FileMode.Create);
- var sw = new StreamWriter(fs);
- sw.Write(str);
- sw.Close();
- fs.Close();
const string str = "put me in a file"; const string file = @"c:\logs\file.txt"; var fs = new FileStream(file, FileMode.Create); var sw = new StreamWriter(fs); sw.Write(str); sw.Close(); fs.Close();
Recommended
- const string str = "put me in a file";
- const string file = @"c:\logs\file.txt";
- File.WriteAllText(file, str);
const string str = "put me in a file"; const string file = @"c:\logs\file.txt"; File.WriteAllText(file, str);
Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)
NOT Recommended
- string input = "sdfds";
- string result = null;
- if (input == null)
- {
- result = "Input is null!";
- }
- else
- {
- result = input;
- }
string input = "sdfds"; string result = null; if (input == null) { result = "Input is null!"; } else { result = input; }Recommended
- string input = "sdfds";
- string result = input ?? "Input is null!";
string input = "sdfds"; string result = input ?? "Input is null!";
This is it for now. If you have more, comment and I’ll add your suggestions to the list (with credits).
Laws of Computer Programming
2. It is easier to change the specification to fit the program than vice versa.
3. If a program is useful, it will have to be changed.
4. If a program is useless, it will have to be documented.
5. Only ten percent of the code in any given program will ever execute.
6. Software expands to consume all available resources.
7. Any non-trivial program contains at least one error.
8. The probability of a flawless demo is inversely proportional to the number of people watching, raised to the power of the amount of money involved.
9. Not until a program has been in production for at least six months will its most harmful error be discovered.
10. Undetectable errors are infinite in variety, in contrast to detectable errors, which by definition are limited.
11. The effort required to correct an error increases exponentially with time.
12. Program complexity grows until it exceeds the capabilities of the programmer who must maintain it.
13. Any code of your own that you haven’t looked at in months might as well have been written by someone else.
14. Inside every small program is a large program struggling to get out.
15. The sooner you start coding a program, the longer it will take.
16. A carelessly planned project takes three times longer to complete than expected; a carefully planned project takes only twice as long.
17. Adding programmers to a late project makes it later.
18. A program is never less than 90% complete, and never more than 95% complete.
19. If you automate a mess, you get an automated mess.
20. Build a program that even a fool can use, and only a fool will want to use it.
21. Users truly don’t know what they want in a program until they use it.
T-SQL: Recently Executed Query
I am a regular reader of Pinal Dave's blog SqlAuthority. I always found something new in his blog to work with SQL Server. Here is something I would like to share: Get the recent executed SQL Queries from SQL Server.
1.SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query] FROM sys.dm_exec_query_stats AS deqs CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest ORDER BY deqs.last_execution_time DESCLimiting the length of a multiline textbox
Limiting the length of an ASP.net mulitline textbox control is easy. Add a RegularExpressionValidator, set the ControlToValidateProperty to the ID of the TextBox you wish to validate and set the ValidationExpression property to :
^[\s\S]{0,300}$This tells the regex validator to limit the number of characters in the Textbox to 300.
Metacharacters
^ Start of Line
[] Character class (list the characters you want to match)
\s White space characters including new line
\S Non-white space characters
{intMin,intMax} Intervals; The minimium number of matches you want to require and the max number of matches you want to allow
Search
Categories
- .NET Framework (3)
- AJAX (3)
- ASP.NET (15)
- ASP.NET 4.0 (5)
- Avengers Infinity War (1)
- C# (1)
- Chess (1)
- Cricket (1)
- Downloads (1)
- Emails (1)
- Ending explained (1)
- General (20)
- gujarat (3)
- Mobiles (1)
- New thing A Day (1)
- Poems (1)
- Programming (1)
- Reviews (1)
- SeminarTopics (1)
- Songs (1)
- SQL Scripts (1)
- Sql Server (3)
- State Server (1)
- Tech (1)
- Visual Studio (6)