2
votes

I am quite new to c sharp.In order to grasp the idea about generic,callback and extension methods i've comp up with the following example.The extension method i wrote will operate on a IEnumerable type and will accept a callback and a integer parameter "year".It will filter out the IEnumerable and return only the item which will pass the test.But while executing the program i've encountered some error :

The type argument for the extension method can not be inferred from the usage

and for the "return item " inside extension method i am getting error : can not implicitly convert type T to System.Collections.Generic.IEnumerable .An explicit conversion exists.

class Program
{
    static void Main(string[] args)
    {
        List<Students> students = new List<Students>();

        students.Add(new Students("zami", 1991));

        students.Add(new Students("rahat", 2012));

        students.FilterYear((year) =>
        {
            List<Students> newList = new List<Students>();

            foreach (var s in students)
            {
                if (s.byear >= year)
                {
                    newList.Add(s);
                }
            }

            return newList;

        }, 1919);

    }
}

    public static class LinqExtend
    {
        public static IEnumerable<T> FilterYear<T>(this IEnumerable<T> source, Func<int, T> callback, int year)
        {
            var item = callback(year);

            return item;
        }
    }

    public class Students
    {
        public string name;

        public int byear;

        public Students(string name, int byear)
        {
            this.name = name;

            this.byear = byear;
        }
    }
1
The extension method also has an issue in that it is return T and not IEnumerable<T> given the function - Nkosi
Is the intended result suppose to be a single item or an enumeration of items? - Nkosi

1 Answers

1
votes

Based on how it was used in the OP the assumption is that the callback was suppose to return an enumeration.

The extension method also has an issue in that it is returning a single T and not IEnumerable<T> given the function.

Update the extension method's callback Func<int, IEnumerable<T>> callback

public static class LinqExtend {
    public static IEnumerable<T> FilterYear<T>(this IEnumerable<T> source, Func<int, IEnumerable<T>> callback, int year) {
        var items = callback(year);
        return items;
    }
}

Given the example in the OP it also looks like you are re-inventing already existing functionality.

You can use LINQ Where to attain the same result.

var year = 1919;
var items = students.Where(s => s.byear >= year).ToList();