Remove Duplicate Items from a Generic List

If you have a List<string> and want to remove duplicate values before binding it to a control, here's how to do so

C#


var strList = new List<string> 

{ "Jane", "Bill", "jane", "carol", "Carol", "bill" }; 

strList = strList.ConvertAll(low => low.ToLowerInvariant());

 

var result = from str in strList

        group str by str into grp

        select new { Text = grp.Key};

foreach (var res in result)

{

    DropDownList1.Items.Add(res.Text);

}



VB.NET


    Dim strList = New List(Of String)(New String() _

                {"Jane", "Bill", "jane", "carol", "Carol", "bill"})

    strList = strList.ConvertAll _

    (Function(low) low.ToLowerInvariant())

 

    Dim result = _

     From str In strList _

     Group str By str Into grp = Group _

     Select New With {Key .Text = str}

    For Each res In result

        DropDownList1.Items.Add(res.Text)

    Next res






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: