简体   繁体   中英

Own programmed LINQ extension methods

Well, I have this extension method:

public static TSource First<TSource>(this IEnumerable<TSource> source)
{ 
    IList<TSource> list = source as IList<TSource>;
    return list[0];
}

And this is how I call it:

doubles.First()

doubles is a list with double numbers

Now I want to use the same extension method for my persons list. This is how I want to call it:

persons.First(x => x.Age < 60)

I should return the first person where the Age is < 60. What do I have to change in my code of the extension method to make this work. At the moment I can't compile because of this error:

CS1501: No overload for method 'First' takes 1 arguments

You need to add a filter or predicate to accomplish what you want to do.

I created this example for you to take a look https://dotnetfiddle.net/BnMktf


using System;
using System.Collections.Generic;
                    

public class Person
{
    public int Age {get; set; }
}

public class Program
{
    public static void Main()
    {
        var persons = new List<Person>();
        persons.Add(new Person() {Age = 60});
        persons.Add(new Person() {Age = 10});
        
        var result = persons.First(p => p.Age < 60);
        var resultWithoutParams = persons.First();
        Console.WriteLine(string.Format("This is the result {0}", result.Age));
        Console.WriteLine(string.Format("This is the result {0}", resultWithoutParams.Age));
    }
}

public static class Extensions {
    public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> filter = null)
    { 
        IList<TSource> list = source as IList<TSource>;
        if(filter == null)
            return list[0];
        
        foreach(var item in list) 
            if(filter(item)) return item;
        
        return default(TSource);
    }
}

this method is only extending the list but It is not accepting any arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM