从Sharepoint的List中获取不重复的item

比如有这么一个表格叫做Movies

Movie          Year

-----          ----

Fight Club     1999

The Matrix     1999

Pulp Fiction   1994

用CAML删选出去年重复的年份,剩下1999,1994绑定到Dropdown Control

由于CAML不能去除重复,只能全部删选出来后,利用DataView实现

            SPList movies = SPContext.Current.Web.Lists["Movies"];

            SPQuery query = new SPQuery();

            query.Query = "<OrderBy><FieldRef Name='Year' /></OrderBy>";



            DataTable tempTbl = movies.GetItems(query).GetDataTable();

            DataView v = new DataView(tempTbl);

            String[] columns = {"Year"};

            DataTable tbl = v.ToTable(true, columns);

DataTable tbl就是只剩下1999,1994了。

还有两个方法能够实现,但是效率不知道哪个好,当数据量一大可能就很会影响性能。

使用客户端对象模型一个对比

foreach (SPListItem listItem in listItems)

    {

        if ( null == ddlYear.Items.FindByText(listItem["Year"].ToString()) )

       {

                   ListItem ThisItem = new ListItem();

                   ThisItem.Text = listItem["Year"].ToString();

                   ThisItem.Value = listItem["Year"].ToString();

                   ddlYear.Items.Add(ThisItem);

        }

   }

使用Linq

// Retrieve the list. NEVER use the Web.Lists["Movies"] option as in the other examples as this will enumerate every list in your SPWeb and may cause serious performance issues

var list = SPContext.Current.Web.Lists.TryGetList("Movies");



// Make sure the list was successfully retrieved

if(list == null) return;



// Retrieve all items in the list

var items = list.GetItems();



// Filter the items in the results to only retain distinct items in an 2D array

var distinctItems = (from SPListItem item in items select item["Year"]).Distinct().ToArray()



// Bind results to the repeater

Repeater.DataSource = distinctItems;

Repeater.DataBind();

 

你可能感兴趣的:(SharePoint)