Use CAML Query to Read Data from lists or Libraries

One way to read the data from a list or a library is to iterate through it using the items collection of the list or library. But this is not the most efficient way to do it, specially if only few items are needed from this list.

Enter CAML Queries.

The following is the example query

		<fieldref name="Title">
			<value type="Text">title</value>

One thing to note in the CAML Query is that there is start and end tag.  It is required that the query string does not have starting and ending tag, otherwise the SPQuery will always return a empty dataset.

And here is the code:

SPList mylist = web.Lists["MyList"];
SPQuery spQuery = new SPQuery();
spQuery.Query = "" //CAML Query String
SPListItemCollection queryitems = mylist.GetItems(spQuery);

That is it, as simple as that.

There as a great tool to build CAML Queries at called U2U Caml Query Builder.  It is worth checking this tool out.