Catch the Unique Items from SharePoint List

I have lot of items from SharePoint List, but most of the items are duplicated. Here, I am going to give you a tips on getting unique rows from the List. For that, I googled for some time and then I found out there is no way to get the items based on CAML.

So I tried to use LINQ to query the SharePoint Items. It works perfectly well for me. Here I provided my code to get the SharePoint Unique ListItems based on latest Items.

In the following example, I am first sorting the Items based on Modified field and then getting the unique item based on Title field by grouping.


using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("MyList");
string Modi = "Modified";
List lstitems =
(from l in list.Items.OfType<SPListItem>() orderby l[Modi] descending select l).ToList<SPListItem>();

var listitemDistinct = lstitems.GroupBy(item1 => item1.Title, (key, group) => group.First()).ToList();

foreach (SPListItem i in listitemDistinct)
{
Console.WriteLine("Title: " +i.Title +"Modified: " + i[Modi].ToString());
}
}
}

If the ListItems has the following items,

ID Title Modified
1 Sample 1 11/16/2011
2 Sample 2 11/17/2011
3 Sample 1 11/18/2011
4 Sample 2 11/19/2011

Result:
Title: Sample 2 Modified: 11/19/2011
Title: Sample 1 Modified: 11/18/2011

Shantha Kumar
Shantha Kumar
Articles: 278

24,849 Comments

  1. Hi,I like your blog’s theme. I too am interested in the same tinchologees as you do. Matter of fact, we’re shifting to MS SP 2007 now to handle all of our online web applications.It is my first time to deal with MS SP, I really would appreciate any thoughts that you might have with regards to what components we’ll need to setup and run the website. I’d love to read any recommendations that you think would help in this project.Hope to see you post again soon.

Comments are closed.