How to remove duplicate items from a generic list

Date Added: August 25, 2010 08:05 by By Edward
Categories: ASP.NET, Other

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.

 

 

Convert enum to String

Date Added: August 12, 2010 08:49 by By Edward
Categories: ASP.NET, Other

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'.

Add a Default ListItem to DropDownList after Databind

Date Added: August 09, 2010 22:20 by By Edward
Categories: ASP.NET

We often want the first option in a dropdown list to be the default item selected. However this can be tricky if you are binding your dropdown list to DataSources like Arrays, ArrayLists, HashTables, DataSets and DataTables. If your preferred option is not available from the list, you will need to add it manually to the list of options. You might prefer to have "Please Select" as the first item in the list. This can be easily done, by binding the dropdown list first, and after the DataBind method, insert a new ListItem as in the example below.

//dsNames already populated from database
ddlNames.DataSource = dsNames
ddlNames.DataTextField="Name";
ddlNames.DataValueField= "Id";
ddlNames.DataBind();

//Add listitem to list and select by default
ddlNames.Items.Insert(0, new ListItem("Please Select", String.Empty));
ddlNames.SelectedIndex = 0;

Reverse a String using C#

Date Added: August 06, 2010 18:49 by By Edward
Categories: ASP.NET, Other

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.

Clear all Objects from Cache

Date Added: July 30, 2010 08:20 by By Edward
Categories: ASP.NET

Caching is one of the least used but a very powerful feature of ASP.NET. It can save you time and also unnecessary trips to the database. If you need to cache any type of information in ASP.NET such as a DataSet, DataTable, or an ArrayList, you can use the cache. This works a lot like a 'session' or 'application variable', but it has some added cache-related methods as well. Scalable web applications should have the ability to store items, whether data objects, pages, or event parts of a page, in memory. This allows you to avoid recreating information, expensive database calls or even connections to 3rd party web services.

However sometimes you might want to clear all these cached objects in one go for some specific reason. Like I said web applications should be scalable and build towards high-performance. This is where you will need to use the 'Cache.Remove()' method, as the built-in cache object in ASP.NET does not support a 'Cache.Clear()' method.

Here is an example of storing a datatable and in the cache:

DataTable dtCacheExample = new DataTable();
//code here: add rows to datatable
Cache["dtCacheExample"] = dtCacheExample;

ArrayList arrCacheExample = new ArrayList();
//code here: add items to arraylist
Cache["arrCacheExample"] = arrCacheExample;

To clear the cache use the following:

// Retrieve a dictionary enumerator used to iterate through the 
// key settings and their values contained in the cache.
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator;

while (CacheEnum.MoveNext) {
    Cache.Remove(CacheEnum.Key.ToString);
}

Catch System.OverflowException caused by a numeric overflow

Date Added: July 28, 2010 21:05 by By Edward
Categories: ASP.NET

As a .NET developer, you can sometimes spend hours finding errors and handling them when you do not know the core logic of the system, and decent good documentation is not that easy to come by. There are several ways to address erros, by using exceptions. Exceptions are designed to handle errors and most commonly in a "try/catch" statement.

It is good practice to not catch the generic errors, and try and debug from there. If you do this, you are unsure what your code is actually doing - which can result in the business living with the concequences. The key is to know which errors you might expect and catch those and handle them accordingly. An exception I found to be hard to track, is the "OverflowException" exception.

From MSDN: An OverflowException exception is thrown when a casting, conversion or arithmetic operation in a checked context results in an overflow. An overflow occurs when an operation produces a value too large for the destination type, infinity, or Not a Number (NaN).

For example, mathematical operations can cause these type of exceptions. A way to check for this error is to use the 'checked' keyword. The 'checked' keyword is used to detect overflow conditions. You should note that an 'OverflowException' exception occurs only in a checked context.

Here is a code example on how to check for this type of exception, and how to handle it.   

 public static void Main()
    {
        try
        {
            checked
            {
                int aInt;
                int bInt;
                int Sum;

                aInt = 2000000000;
                bInt = 2000000000;
                Sum = aInt + bInt;
            }
        }
        catch (OverflowException oExcep)
        {
            Console.WriteLine("A mathematical operation caused an overflow.");
            // Good idea to log this error and deal with it when doing debugging
            // I am using my own Logging module.
            Logger.LogException(oExcep, "A mathematical operation caused an overflow.");
        }
    }

Select unique rows from a DataTable

Date Added: July 26, 2010 08:22 by By Edward
Categories: ASP.NET, Other

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.

Generating XML Comments with GhostDoc

Date Added: July 20, 2010 08:26 by By Edward
Categories: ASP.NET, Development Resources, Other

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.

GhostDoc comments

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:

  • VB.NET
  • C#

Download it from here:

http://visualstudiogallery.msdn.microsoft.com/en-us/46A20578-F0D5-4B1E-B55D-F001A6345748

Using the Environment class for getting and setting various operating system related information

Date Added: June 24, 2010 20:21 by By Edward
Categories: ASP.NET, Other

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));
        }


    

The 'is' operator in C#

Date Added: June 04, 2010 06:51 by By Edward
Categories: ASP.NET, Other

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.

 

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net