LINQ Select Statement Using Anonymous Types in C#

by a Guest on October 14, 2010 0 Comments

public void UpperCaseLowerCase()
{
    string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };

    var upperLowerWords =
        from w in words
        select new {Upper = w.ToUpper(), Lower = w.ToLower()};

    foreach (var ul in upperLowerWords) {
        Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
    }
}

// Result

Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry

LINQ Select Statement in C#

by a Guest on October 14, 2010 0 Comments

Example of a LINQ Select statement where the method adds 1 to the number and prints them out:

public void AddOneToValue()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var numsPlusOne =
        from n in numbers
        select n + 1;
   
    Console.WriteLine("Numbers + 1:");

    foreach (var i in numsPlusOne)
    {
        Console.WriteLine(i);
    }
}

// Result

Numbers + 1:
6
5
2
4
10
9
7
8
3
1

Replace First or Last Occurrence of a String in C#

by a Guest on October 14, 2010 0 Comments

This snippet provides two functions to replace only the first or the last occurrence of a string within a larger string. Using the Replace method will replace all occurrences found.

public static string ReplaceFirstOccurance(string Source, string Find, string Replace)
{
    int Place = Source.IndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}
 
public static string ReplaceLastOccurance(string Source, string Find, string Replace)
{
    int Place = Source.LastIndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}

View the original article here

String to byte[] and byte[] to String in C#

by a Guest on October 14, 2010 0 Comments

These two methods allow conversion between a C# byte array and string, and vice versa. Handy in dealing with COM objects and some .Net Providers (IBM CWBX, EventLog and so on).

String to byte array:

public static byte[] StrToByteArray(string str)
{
    System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}

Byte array to string:

public static string ByteArrayToStr(byte[] byteArray)
{
  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  return encoding.GetString(byteArray);
}

View the original article here

Foreach Loop Over Hashtable in C#

by a Guest on October 14, 2010 0 Comments

This short snippet will run a foreach loop over a hashtable giving you access to the key and value pair.

foreach (string key in hash.Keys)
{
  Console.WriteLine(key + '=' + hash[key]);
}

View the original article here

Lorem Ipsum Generator in C#

by a Guest on October 14, 2010 0 Comments

This class will create a Lorem Ipsum generator that can be used to create the famous "Lorem ipsum dolor sit amet" used to dummy text.

using System;
using System.Text;
 
/// <summary>
/// Lorem Ipsum generator class for C#
/// </summary>
public class Ipsum
{
  private string[] words = new string[] { "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod",
    "tempor", "invidunt", "ut", "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed", "diam", "voluptua",
    "at", "vero", "eos", "et", "accusam", "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita",
    "kasd", "gubergren", "no", "sea", "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet",
    "lorem", "ipsum", "dolor", "sit", "amet", "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod",
    "tempor", "invidunt", "ut", "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed", "diam", "voluptua",
    "at", "vero", "eos", "et", "accusam", "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita",
    "kasd", "gubergren", "no", "sea", "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet",
    "lorem", "ipsum", "dolor", "sit", "amet", "consetetur", "sadipscing", "elitr", "sed ...

read more

How to Obtain Current Application Directory in C#

by a Guest on October 14, 2010 0 Comments

From time to time you may need to access a file within the current application folder. .Net provides a property that is set to the absolute path to the application executable, and a method can be used to extract the folder name.

using System.IO;
using System.Windows.Forms;
 
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

Note: Console Application project types will have to manually add a reference to the System.Windows.Forms assembly for the Application object to be exposed.

View the original article here

File Directory Listing in C#

by a Guest on October 14, 2010 0 Comments

This little snippet will process a directory and get a list of all the files in the directory, returning them as a StringBuilder object:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      StringBuilder dirList = directoryListing("C:\\Inetpub", "");
      Console.WriteLine(dirList.ToString());
    }
 
    static StringBuilder directoryListing(string path, string indent)
    {
      StringBuilder result = new StringBuilder();
      DirectoryInfo di = new DirectoryInfo(path);
      DirectoryInfo[] rgDirs = di.GetDirectories();
 
      foreach (DirectoryInfo dir in rgDirs)
      {
        result.AppendLine(indent + dir.Name);
        result.Append(directoryListing(path, indent + "..").ToString());
      }
      return result;
    }
  }
}

View the original article here

Using Regular Expression in C# to Check Email Address Validity

by a Guest on October 14, 2010 0 Comments

Regular expressions are special strings that are used to describe a search pattern. They can be used for data validation, data processing and pattern matching.

Regular Expressions (regex for short) are language and platform independent so an expression for Perl will work on PHP and C#. Regex start with a caret (^) character and end with a dollar ($) symbol. The text in between these two characters is used to match a string.

Regular expressions in C# are defined within the System.Text.RegularExpressions namespace which provides a Regex class. When instantiating the class you need to pass the expression string to the constructor. We have used a verbatim string for the regex as it makes the regex easier if you don't have to escape forward slashes.

In this example we test two strings to see if they contain a valid email address. The emailRegex will match any valid email address ...

read more

Testing C# Code Performance Speed

by a Guest on October 14, 2010 0 Comments

Programming with C#, as in a lot of languages, gives an infinite amount of ways to write applications. All the different programming pratices can vary your application's speed and efficiency. Determening which coding techniques are faster is an essential skill.

The algorithm to test out fast and efficient C# source code run is:

-> Initialize variables needed

-> Declare a System.Diagonistic.StopWatch varible.

-> Include this line before starting the test: [StopWatch variable].Start();

-> Setup a for loop with the code to be tested inside

-> The amount of trials should be set up in such a way that the total execute time lasts an appropriate duration

-> Execute this line to stop the StopWatch: [StopWatch variable].Stop();

-> Initialize a new TimeSpan variable with: TimeSpan span = new TimeSpan([StopWatch variable].ElapsedTicks);

-> The span variable has the amount of time the source took to run

An optional part is to divide the time it ...

read more
Older Posts Page 1 of 2.

Post categories

Post archives