简体   繁体   中英

C#: generic function that return element from collection based on condition

So i have this function that return element from collection based on condition

public static T Search<T>(IEnumerable<T> source, Func<T, bool> filter)
{
    return source.FirstOrDefault(filter);
}

And i want to convert this to return all the elements form my collection that mach my condition .

so instead of change the function signature to public static IEnumerable<T> Search<T>(IEnumerable<T> source, Func<T, bool> filter)

What i need to changed inside my function ?

Use Where instead of FirstOrDefault

public static IEnumerable<T> Search<T>(IEnumerable<T> source, Func<T, bool> filter)
{
    return source.Where(filter);
}

使用 Where 方法而不是 FirstOrDefault

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