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

No comments:

Post a Comment