Reputation: 753
Trying the following code (found here):
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var a = new List<int> { 1, 2, 3 };
var b = new List<int> { 1, 2, 3, 4, 5 };
var xxx = a.Merge(b, (x, y) => x + y);
foreach (var c in xxx)
{
Console.WriteLine(c);
}
}
static IEnumerable<T> Merge<T>(this IEnumerable<T> first,
IEnumerable<T> second, Func<T, T, T> operation)
{
using (var iter1 = first.GetEnumerator())
using (var iter2 = second.GetEnumerator())
{
while (iter1.MoveNext())
{
if (iter2.MoveNext())
{
yield return operation(iter1.Current, iter2.Current);
}
else
{
yield return iter1.Current;
}
}
while (iter2.MoveNext())
{
yield return iter2.Current;
}
}
}
}
}
I get this error:
'System.Collections.Generic.List' does not contain a definition for 'Merge' and no extension method 'Merge' accepting a first argument of type 'System.Collections.Generic.List could be found (are you missing a using directive or an assembly reference?)
Which makes sense. But since I am not sure on how the code should work and I want to fully understand it...
How to fix this problem?
Upvotes: 1
Views: 245
Reputation: 16956
Move your extension method to separate static
class.
public static class Extensions
{
public static IEnumerable<T> Merge<T>(this IEnumerable<T> first,
IEnumerable<T> second, Func<T, T, T> operation)
{
using (var iter1 = first.GetEnumerator())
using (var iter2 = second.GetEnumerator())
{
while (iter1.MoveNext())
{
if (iter2.MoveNext())
{
yield return operation(iter1.Current, iter2.Current);
}
else
{
yield return iter1.Current;
}
}
while (iter2.MoveNext())
{
yield return iter2.Current;
}
}
}
}
You can find working fiddler sample here
Upvotes: 1
Reputation: 100527
Extension must be defined in static class - https://msdn.microsoft.com/en-us/library/bb311042.aspx.
Fix: make sure your Program
class that contains Main
is static.
static class Program
{
private static void Main() ....
Note: proper fix would be to move the Merge
extension method to separate static class in the same namespace or other namespace that is included with using
.
Upvotes: 3