Pages

Friday, February 28, 2014

HOW TO: Remove Duplicate Data using LINQ

Few days back i needed to remove duplicate ITEM_ID field values of  queried data using LINQ..

So basicly all I had to do is to Group the results by ITEM_ID and then select the first returned data in each group:

var queryResult = dataVar.Contents
.OrderByDescending(o => o.ITEM_ID)
.Where(x => x.userNAME.Contains(searchKeyTxtBx.Text))     \\ filter the data
.GroupBy(p => p.ITEM_ID)    \\ Group By Item ID
.Select(g => g.First())     \\ select the first in each group
.ToList();     \\ final data have NO duplicate ITEM_ID values

HOW TO: Add a default ListItem to a DropDownList

This post shows you how to add as many ListItems to a DropDownList before having DB databind on the same DropDownList .. It can be done one of 2 ways. A default ListItem can be added to a DropDownList programmatically with the following syntax after binding data to the DropDownList:
 
//Code here to populate DropDownList
DropDownListID.Items.Insert(0, new ListItem("Default text", "Default value")
This will add a ListItem to index 0, which will be the first ListItem.
In .NET 2.0, this can be done declaratively using the AppendDataBoundItems property. This will append all data-bound ListItems to the DropDownList, leaving those you add manually as the first selections.
<asp:DropDownList ID="DropDownListID" AppendDataBoundItems="true" runat="server">
     <asp:ListItem Text="Default text" Value="Default value" />
</asp:DropDownList>

Setting AppendDataBoundItems=True Property ensures that your datasource items will be appended without removing the initial item.