There are many ways to remove duplicate elements from a generic List collection in the C# language, but some are easier to implement then other, or some might not fit your code. An easy solution, is using the LINQ extension methods can be very useful when you have a List collection. It is lightweight, and is can also be implemented anywhere in your solution.
For my example, I used the Linq "Distinct" method (System.Linq) to get a unique list of categories for books. I first get a list of my books from the database, and then use the "distinct" method, and then also cast the list back to a generic list with the duplicate items removed.
/// <summary>
/// Returns the distinct list of categories.
/// </summary>
/// <returns>List<string></returns>
private static List<string> ReturnDistinctListofCategories()
{
// List with duplicate elements.
List<string> list = new List<string>();
list.Add("code");
list.Add("coding");
list.Add("asp.net");
list.Add("tips");
list.Add("code");
list.Add("coding tips");
list.Add("asp.net tips");
// We now have a list with duplicate items
// Get distinct elements and convert into a list again.
List<string> distinctClientList = list.Distinct().ToList();
//DEBUG: Test the result
foreach (string value in distinctClientList)
{
Debug.WriteLine(value);
}
return distinctClientList;
}
I hope this can help you. Like I stated before, there are numerous ways to do the same as my code.
ed683bc3-4e68-4d25-b7cc-24b804ec9fe4|0|.0
Microsoft announced that they are going to unveil Internet Explorer 9 (IE9) "Beta" next month(September 2010), at an event in San Francisco titled Beauty of the Web. While the browser wars for top spot are now between Internet Explorer, Firefox, Chrome and Opera, the latest version of IE9 will have to catch-up quickly. Microsoft seems to have missed a golden opportunity to make up for the failures of IE6 and IE7. Even Safari is making IE seem like an old browser and that is not even a target Windows platform browser.
By bringing out IE9 Microsoft seems to take something from Firefox Chrome. Some of the key features are that there are improved standards supports, as it scored an impressive 95% on the Acid 3 CSS test. IE9 also have better JavaScript and graphics performance, compared to previous versions. IE9 also implements enough of the HTML5 specification to raise the hope that stuffing rich content into browser plug-ins might not always be necessary.
As Microsoft is stating on its IE blog "IE9 offers consistent, fully hardware-accelerated text, graphics, and media, both audio and video", let’s hope Microsoft is starting to catch up and will continue to give users what they want from a browser experience.

47ded78a-ee2a-440a-81d0-704e493f3bb4|0|.0
If you are working with Enumerations (enum) in C#, you will know how easy it is to use within your code. Enum's are strongly typed constants which are unique types and allows you to assign symbolic names to integral values.
Enum is also a reserved keyword and is a value type, which means we can use it as a string, if the need arises. I have added an example where I would like to write out the Gender value of a enum. Because I can't just write the value to screen, I need to convert it to a string, which is actually very easy.
The following example demonstrates converting an enumerated value to a string.
public class GenderSample {
enum Gender {Male = 1, Female = 2};
public static void Main() {
Enum GenderOptions = Gender.Male;
Console.WriteLine("The value of this instance is '{0}'",
GenderOptions.ToString());
}
}
Output: The value of this instance is 'Male'.
c8ce2f91-df20-4652-a1f3-966d8901be11|0|.0
This week I was asked by a friend how you would reverse a sentence, with minimial effort and that works in all scenarios. This was a nice challenge for me, so started working on something.
I first though of using recursion with a substring method to reverse the sentence, which worked fine, however this looked a bit messy and I thought it might impact on the performance of the program. I searched MSDN and the ASP.NET website for an alternative option, and surprisingly I found an article which Justin Rogers wrote, which did exactly what I was looking for... You can use the 'Array.Reverse()' method that is already provided to you by the .Net framework.
Here is an example of how to efficiently reverse the characters in a string:
static public string Reverse(string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
Input: Hello World
Output: dlroW olleH
The example above is just for demostration. In my case, I was using large strings, therefore this method was the preferred option. In some cases you can use recursion with a substring method, which will be a better choice on performance.
I though I would share Justin's article, so you can read it here.
71ef8e12-950f-4e5b-86b5-b5a06cfe75b4|0|.0
The LINQ distinct select method is a powerful small method that can help you select unique entries from datatable.
The following example will return a datatable with unique results, from a datatable which can be populated from a database. The following example uses a datatable I created to show you how the LINQ distinct select method works.
The example below have a list of users, but I only want the 'user names' to be returned. They have to be unique, as I might want to use it in a report.
/// <summary>
/// Gets the user names.
/// </summary>
public static void GetUserNames()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(int));
dt.Columns.Add("UserName", typeof(string));
dt.Rows.Add(1, "Joe Smith");
dt.Rows.Add(2, "John Doe");
dt.Rows.Add(3, "Joe Smith");
dt.Rows.Add(4, "Jane Smith");
dt.Rows.Add(5, "Jane Doe");
DataTable filterTable = GetUniqueEntries(dt);
}
/// <summary>
/// Gets the unique entries.
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns></returns>
private static DataTable GetUniqueEntries(DataTable dt)
{
var query = (
from row in dt.AsEnumerable()
select row.Field<string>("UserName")).Distinct();
DataTable dtDistinctNames = new DataTable();
dtDistinctNames.Columns.Add("UserName", typeof(string));
//have to return a datatable, thus loop through entries
foreach (string item in query)
{
DataRow newRow = dtDistinctNames.NewRow();
newRow["UserName"] = item;
dtDistinctNames.Rows.Add(newRow);
}
return dtDistinctNames;
}
This code snippet will return you a list of users where 'username' are unique. There eliminating duplicate names from the list. There are alternative ways to do this type of functionality - this blog entry is created to show you how easy it can be to use LINQ with C# code.
77ed5066-4f9b-45fb-9725-1cc8c29d782d|2|2.5
GhostDoc is a free Visual Studio extension which I stumbled accross while looking for something to help me with commenting my code. GhostDoc automatically generates XML documentation comments for methods and properties based on their type, parameters, name, and other contextual information. It takes the 'pain' out of commenting each method word for word - saving you time doing what you do best - coding!
Most documentation created will be a waste of time for a developer, and usually when there is no time to waste a developer might find the documentation is slowing him down. For any decent documentation to be useful, a developer must know that when the documentation was initially generated it was both correct and complete, it has also been updated as the project scope changed, or amendments was made to the code. I ofter find code to out of sync with documentation, which leaves me with lots of 'catch up' to do, before I feel in control and productive.
You can set it up, so when you right click on a method the "Document This" option becomes available that allows you to generate summary comments for your method.

Here is an example of summary comments I created using this tool.
/// <summary>
/// Checks for SQL injection.
/// </summary>
/// <param name="userInput">The user input.</param>
/// <returns></returns>
public static string checkForSQLInjection(string userInput)
{
// code here
}
It is also supported in the following versions of the Visual Studio IDEs:
- Visual Studio 2010
- Visual Studio 2008
- Visual Studio 2005
Supported Languages:
Download it from here:
http://visualstudiogallery.msdn.microsoft.com/en-us/46A20578-F0D5-4B1E-B55D-F001A6345748
bd1895d8-088a-4b01-bc9c-c2b3d4da826e|1|4.0
The "Environment" class of the System namespace is handy for getting and setting various operating system related information. The "Environment" class to retrieve information such as the current directory, network details, machine name, OS versions, environment variable settings, contents of the call stack, time since last system boot, and the version of the common language runtime.
There is a lot of information that can be extracted with the "Environment" class. Below is a small code snippet that might help you get started.
public static void GetEnvironmentDetails()
{
Console.WriteLine();
Console.WriteLine("-- Environment members --");
// Invoke this sample with an arbitrary set of command line arguments.
Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
String[] arguments = Environment.GetCommandLineArgs();
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
// <-- Keep this information secure! -->
Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
// <-- Keep this information secure! -->
Console.WriteLine("MachineName: {0}", Environment.MachineName);
Console.WriteLine("OSVersion: {0}", Environment.OSVersion);
Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
// <-- Keep this information secure! -->
Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
Console.WriteLine("TickCount: {0}", Environment.TickCount);
// <-- Keep this information secure! -->
Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
// <-- Keep this information secure! -->
Console.WriteLine("UserName: {0}", Environment.UserName);
Console.WriteLine("Version: {0}", Environment.Version);
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.System));
String[] drives = Environment.GetLogicalDrives();
Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
}
41ec2b83-c8de-4281-852f-b801e05e233b|0|.0
The 'is' operator is used to check whether the run-time type of an object is compatible with a given type, and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.
For example:
public static void RunThis()
{
// For this example the following obj is a class already created
object obj = new MyClass();
CastCheck(obj);
}
public static void CastCheck(object obj)
{
// For this example the following classes are already created
Class1 a;
Class2 b;
if (obj is Class1)
{
Console.WriteLine("obj is Class1");
a = (Class1)obj; // do something with a
}
else if (obj is Class2)
{
Console.WriteLine("v is Class2");
b = (Class2)obj; // do something with b
}
else
{
Console.WriteLine("obj is neither Class1 nor Class2.");
}
}
The 'is' operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.
aa01e2db-916a-47ec-bcf9-5a2faf80e9f4|0|.0
The 'as' operator is a "type", and is just like the cast operator except that it will return NULL on a conversion failure instead of throwing an exception. The 'as' operator is used to perform conversions between compatible types and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.
For example:
Object objValue = new Object();
string strA = (string)objValue; //Cast throws an Exception
string strB = objValue as string; //No exception is thrown, but strB is set to NULL
The 'as' operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.
d068c41b-f1e6-44cf-b775-829302744af6|0|.0
The phrase "iterating through a directory tree" can also mean "iterating through a folder tree structure". Both statements are valid, when you talk about Windows 'directories' of 'folders'. Iteration means to access each file in each nested subdirectory under a specified root folder, to any depth, unless you specify how many levels 'down' you would like to search. You do not necessarily have to open each file. You can just retrieve the name of the file or subdirectory as a string, or you can retrieve additional information in the form of a System.IO.FileInfo or System.IO.DirectoryInfo object.
The following example shows how to iterate through files and folders in a directory tree without using recursion. You should be careful to modify this code to suit your needs.
static void Main()
{
//Specify the starting folder
string folder = "C:/myfolder/tips/dascode/";
RetrieveTreeStructureFiles(folder);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void RetrieveTreeStructureFiles(string root)
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack dirs = new Stack(2);
if (!System.IO.Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (string file in files)
{
try
{
// Perform whatever action is required in your scenario.
System.IO.FileInfo fi = new System.IO.FileInfo(file);
Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
}
foreach (string str in subDirs)
{
dirs.Push(str);
}
}
}
f15a2334-2bd0-4400-ac9b-f1fdc954f50c|0|.0