How to remove duplicate items from a generic list

by Edward 25 August 2010 08:05

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.

 

 

Tags: , ,

ASP.NET | Other

IE9 Beta to be released this September

by Edward 17 August 2010 21:22

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.

Tags: , ,

Other | Technology

Convert enum to String

by Edward 12 August 2010 08:49

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

Tags: , ,

ASP.NET | Other

Add a Default ListItem to DropDownList after Databind

by Edward 09 August 2010 22:20

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;

Tags: , ,

ASP.NET

Reverse a String using C#

by Edward 06 August 2010 18:49

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.

Tags: , , ,

ASP.NET | Other

About DasCode.Net

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

Code... that's .net

Month List