31 Agu 2010

Simple LINQ Example on Sharepoint Items Query

Actually I don’t remember much about CAML that came up with Sharepoint. CAML is a basic XML based query to fetch some item based on criteria, just like query on SQL. But, It’s so hard to remember! I want to run code as fast as I can, and here’s the answer, LINQ. So, can we start and try this?

OK, before we start, we must ensure that we have .NET Framework 3.5, coz that’s the framework to do the LINQ, and import System.Core.dll to your project. and add the imports below.

using System.Collections;
using System.Collections.Generic;
using System.Linq;

LINQ gives you so many solution to get queries easily, and you don’t need to remember CAML or whatever you’ve called. You can get raw IEnumerable<SPListItem> from the LINQ, but if you want to iterate through query result, you must use foreach.

IEnumerable<SPListItem> LiColl = from SPListItem Li in Lhr.Items where Convert.ToDateTime(Li[SPD.ReplaceFieldSpaceName("Tanggal Kelahiran")].ToString()).Subtract(DateTime.Today).Days <= 0 &&
Convert.ToDateTime(Li[SPD.ReplaceFieldSpaceName("Tanggal Kelahiran")].ToString()).Subtract(DateTime.Today).Days >= (_DayIndex * -1) select Li;

Another way, you can get items, using IList<SPListItem> and you can iterate with any iterator.

IList<SPListItem> LiColl2 = (from SPListItem Li in Lhr.Items where Convert.ToDateTime(Li[SPD.ReplaceFieldSpaceName("Tanggal Kelahiran")].ToString()).Subtract(DateTime.Today).Days <= 0 && Convert.ToDateTime(Li[SPD.ReplaceFieldSpaceName("Tanggal Kelahiran")].ToString()).Subtract(DateTime.Today).Days >= (_DayIndex * -1) select Li).ToList();

And the other way, you can get items, and returning array of SPListItem.

SPListItem[] LiColl3 = (from SPListItem Li in Lhr.Items where Convert.ToDateTime(Li[SPD.ReplaceFieldSpaceName("Tanggal Kelahiran")].ToString()).Subtract(DateTime.Today).Days <= 0 && Convert.ToDateTime(Li[SPD.ReplaceFieldSpaceName("Tanggal Kelahiran")].ToString()).Subtract(DateTime.Today).Days >= (_DayIndex * -1) select Li).ToArray();

Tidak ada komentar:

Posting Komentar

[give me your ideas, hopes, comments and compliments below...]
[aaand...... +1 if you need to....]