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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>