patterncsharpMinor
Is ToIEnumerable<T> good practice?
Viewed 0 times
practicetoienumerablegood
Problem
I have an extension method that does this:
I need to be able to convert any object to an
For example when I use the .NET
I can call
Is
public static IEnumerable ToIEnumerable(this T source) where T : new()
{
return new[] { source };
}I need to be able to convert any object to an
IEnumerable.For example when I use the .NET
Except method:public static IEnumerable Except(this IEnumerable first)I can call
Except by doing the following:return objects.Except(this.ToIEnumerable());Is
ToIEnumerable good practice or should I solve the problem in differently?Solution
While I don't see why
or possibly
Not only will this perform better than Except here, but it's easier to understand, and avoids the entire ToIEnumerable thing entirely.
ToIEnumerable is bad practice, in this specific case I think it is. You're comparing with only one object; why not just attach a where clause on to things? I.e.return objects.Where((other) => other != this);or possibly
return objects.Where((other) => !Object.ReferenceEquals(other, this));Not only will this perform better than Except here, but it's easier to understand, and avoids the entire ToIEnumerable thing entirely.
Code Snippets
return objects.Where((other) => other != this);return objects.Where((other) => !Object.ReferenceEquals(other, this));Context
StackExchange Code Review Q#836, answer score: 7
Revisions (0)
No revisions yet.