自己编程的LINQ扩展方法



好吧,我有这个扩展方法:

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

我就是这样称呼它的:

doubles.First()

doubles是一个具有双数字的列表

现在,我想对我的persons列表使用相同的扩展方法。我想这样称呼它:

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

我应该返回年龄<60.我必须在扩展方法的代码中更改什么才能使其工作。目前我无法编译,因为这个错误:

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

您需要添加一个筛选器或谓词来完成您想要做的事情。

我创建了这个例子让你看看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);
}
}

此方法只是扩展列表,但不接受任何参数。

最新更新