Skip to content

Instantly share code, notes, and snippets.

@xinmyname
Created June 7, 2012 04:41
Show Gist options
  • Save xinmyname/2886614 to your computer and use it in GitHub Desktop.
Save xinmyname/2886614 to your computer and use it in GitHub Desktop.
SharePoint object mapper
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Microsoft.SharePoint;
namespace MileageSite.Layouts.MileageSite
{
public static class SPListItemExtensions
{
public static IEnumerable<T> Map<T>(this SPList list)
{
return from SPListItem item in list.Items select item.Map<T>();
}
public static T Map<T>(this SPListItem item)
{
var obj = (T)Activator.CreateInstance(typeof(T));
foreach (PropertyInfo info in typeof(T).GetProperties())
{
object value = item[info.Name];
if (value == null)
info.SetValue(obj, null, null);
else if (value.GetType() == info.PropertyType)
info.SetValue(obj, value, null);
else if (info.PropertyType == typeof(SPUser))
{
SPField field = item.ParentList.Fields.GetFieldByInternalName(info.Name);
var itemValue = (SPFieldUserValue)field.GetFieldValue((string)value);
info.SetValue(obj, itemValue.User, null);
}
else
{
TypeConverter converter = TypeDescriptor.GetConverter(info.PropertyType);
object convertedValue = converter.ConvertFrom(value);
info.SetValue(obj, convertedValue, null);
}
}
return obj;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment