I want to query a Sharepoint 2007 list called valueList
via web service and find the most recent version of each list item, so given this list:
ID | Value
----------
1 | 101
2 | 305
3 | 102
4 | 101
5 | 305
6 | 101
I want my query to return:
ID | Value
----------
3 | 102
5 | 305
6 | 101
In Access SQL, I would do this with:
select v1.* from valueList v1
inner join
(select value, max(id) as maxID from valueList group by value) v2
on v1.id=v2.maxID
So far it seems like the only way I can do this in C#/CAML/Sharepoint web service is to run a CAML query to group my list items by value
and order them by ID
, dump the query to a DataTable, then go through every row of the DataTable, picking the last row for each value
. Code as follows:
//dataHandler constructor initializes Web Services Lists() object
dataHandler dh = new dataHandler();
string[] fields = { "ID", "value"};
string query =
"<GroupBy collapse='true'>" +
"<FieldRef Name='value' />" +
"</GroupBy>" +
"<OrderBy>" +
"<FieldRef Name='ID' />" +
"</OrderBy>";
DataTable listTable = dh.listToDataTable("valueList", fields, query);
//copy listTable structure to blank resultTable
DataTable resultTable = listTable.Clone();
//initialize value
int value = (int)Convert.ToDouble(listTable.Rows[0][1]);
for (int ctr = 0; ctr < listTable.Rows.Count; ctr++)
{
//check to see if we've gone onto a new 'value', if so get previous row
if (value != (int)Convert.ToDouble(listTable.Rows[ctr][1]) )
{
resultTable.ImportRow(listTable.Rows[ctr - 1]);
value = (int)Convert.ToDouble(listTable.Rows[ctr][1]);
}
//get the last row
if (ctr == listTable.Rows.Count - 1)
{
resultTable.ImportRow(listTable.Rows[ctr]);
}
}
The (int)Convert.ToDouble
is because the field is stored as a string in the DataTable, e.g. 1234 gets stored as "1234.0000".
This seems unnecessarily complicated; is there a more direct way to accomplish what I'm after? I'm not required to use DataTables or CAML, if there's something easier.
value
field; I would still have to run a For loop through the datatable to get the highest ID for each value. Or am I missing something? – sigil May 29 '12 at 14:47