Search code examples
c#sharepoint-2010for-loopforeachsplistitem

Looping thorugh selective SharePoint List columns


I have a share-point list called "Employees". I have the following columns:

  • Title
  • FirstName
  • LastName
  • Band1
  • Band2
  • Band3
  • Band4

I have 20 band columns, but I have only included 4 band columns in order to better explain the problem. I know how to get data from specific columns, but how do I go about doing the following:

  1. Get total number of "Band" columns only from the list above
  2. Loop through each "Band" column and get/display the items/values in each of the bands

My first though it to have a loop that loops through all the band columns, then have a loop inside that to get/display each item/value inside of each band but I am not entirely sure how to go about it doing it

Any ideas or suggestion would greatly appreciated,

Thanks,


Solution

  • To get all the Band fields, I'd do something like

    var fieldLookup = mySpList.Fields.Cast<SPField>()
        .Where(f => f.Title.StartsWith("Band"))
        .Select(f => { 
                int bandNo;
                bool successful = int.TryParse(f.Title.Substring(4), out bandNo);
                return new { Id = f.Id, BandNo = bandNo, Success = successful };
            })
        .Where(a => a.Success)
        .ToDictionary(a => a.BandNo, a => a.Id);
    

    This should get you a Dictionary<int, Guid> that maps the band number from the column heading to the ID of the field.

    You can then use these IDs to fetch the values. For example, you can build a list of <FieldRef> elements to pass into an SPQuery, or you can just do

    foreach (SPListItem item in myList.Items)
    {
        Console.WriteLine("Item {0}", item.Title);
        foreach(int bandNo in fieldLookup.Keys)
        {
            Console.WriteLine("Band {0}: {1}", bandNo, item[fieldLookup[bandNo]]);
        }
    }