Generating Columns For An SPGridView With LINQ (Extension Method)

More a small development note for myself since I generally end up using all the columns in a list when developing with SPGridView’s.

[csharp]
private static void GenerateColumns(this SPGridView gridView, SPList list )
{
gridView.AutoGenerateColumns = false;
foreach( var column in from string fieldname in list.DefaultView.ViewFields
select list.Fields.GetFieldByInternalName( fieldname )
into field
select new BoundField
{
DataField = field.StaticName,
HeaderText = field.Title
} )
{
gridView.Columns.Add( column );
}
}

[/csharp]

Share

Remove Duplicates From Strongly Typed Collections With Extension Methods

 Just a quick note to myself in case I begin the horrendous search for this again, the best / most performant way I have found to remove duplicates follows this structure:

[csharp]
public static class Extensions
{
public static IEnumerable RemoveDuplicates(this IEnumerable source)
{
return RemoveDuplicates(source, (t1, t2) => t1.Equals(t2));
}

public static IEnumerable RemoveDuplicates(this IEnumerable source, Func equater)
{
var result = new List();
foreach (var item in source.Where(item => result.All(t => !equater(item, t))))
{
result.Add(item);
}
return result;
}
}
[/csharp]

Share

Getting Safe String Values

I know there are better ways of getting SharePoint field values then indexing the SPListItem for a particular field and using archaic string manipulation to make things dance. But sometimes when you are retrofitting a legacy application it can be intrusive to the holistic application and cause all sorts of issues in other portions.

While doing a code review today at a client this came up. We were discussing when using the SPListItem indexing approach how to best get safe string values. The extension method in use that we were discussing today was:

[csharp]
public static string ToSafeString(this T obj)
{
if (typeof(T).IsValueType)
{
return obj.ToString();
}
return Equals(obj, null) ? string.Empty : obj.ToString();
}

[/csharp]

Now I don’t think that this is too bad, but doesn’t Convert.ToString() already handle null values? I guess I can see the use since it will show on every derived class depending on the implementation of the extension and might look more natural from a language perspective. Furthermore, I find the value type guard clause unnecessary, and could be simply truncated as written as a helper method i.e.:

[csharp]
return value == null ? string.Empty, obj.ToString();
[/csharp]

Share