Created
June 7, 2012 04:41
-
-
Save xinmyname/2886614 to your computer and use it in GitHub Desktop.
SharePoint object mapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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