Home
Register
About
Login
Categories
C#
(13)
VB.NET
(0)
F#
(0)
ASP.NET
(15)
JavaScript
(4)
C++
(0)
C
(0)
Python
(0)
Ruby
(0)
Rails
(0)
J#
(0)
SQL
(0)
VB Script
(0)
HTML
(0)
CSS
(2)
XML
(2)
XSLT
(0)
Unit Testing
(7)
Architecture
(2)
Ajax
(0)
Project Management
(0)
LINQ to SQL
(2)
LINQ
(0)
LINQ to XML
(1)
NHibernate
(0)
Active Record
(0)
Silverlight
(0)
ASP.NET MVC
(0)
Life
(0)
Book Reviews
(0)
WPF
(1)
Visual Studio
(0)
Convert Object to IEnumerable
by azamsharp on 5/31/2008 4:22:10 PM
I had to bind an object to a GridView control. The GridView supports binding using ListSource or IEnumerable. So, I changed my object to IEnumerable
. Here is my code.
public static IEnumerable<T> AsIEnumerable<T>(this T item)
{
List<T> list = new List<T>();
list.Add(item);
return list;
}
Refactor it!
For my first refactoring session on this site I suggest a few improvements: First rename the method to AsEnumerable. The extra 'I' in the method name doesn't add any value and renaming it will make it consistent with the LINQ Enumerable.AsEnumerable extention method. Second return a plain old array, this is more readable and besides that, saves us an allocation on the GC heap (a List
is a clearer wrapper around an array). Optionally you could even use 'yield return item' instead of 'return new T[] { item };'. This is possibly even better for performance, because this again saves an extra object allocation (where the GetEnumerator() method of the array class returns a new IEnumerator object, the GetEnumerator method of the generated class, will simply return itself, because it implements both IEnumerable and IEnumerator). Down side is that your class library increases in size, because of the extra code generated by the C# compiler. (I'd personally stick with return new T[]).
by .NET Junkie on 6/13/2008 1:34:09 AM
public static IEnumerable<T> AsEnumerable<T>(this Titem)
{
return new T[] { item };
// or: yield return item;
}
I agree with you! Thanks for the refactoring! Keep em coming!
by azamsharp on 6/13/2008 7:44:44 AM
Please log in to refactor the code!
Login