【问题标题】:C#: generic function that return element from collection based on conditionC#:根据条件从集合中返回元素的通用函数
【发布时间】:2018-10-08 15:59:47
【问题描述】:

所以我有这个function,它基于conditioncollection返回元素

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

我想将其转换为从我的collection 中返回所有的elements,这与我的condition 相当。

所以不要将函数签名更改为public static IEnumerable&lt;T&gt; Search&lt;T&gt;(IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; filter)

我需要在我的函数中更改什么?

【问题讨论】:

  • return source.Where(filter); 工作吗?
  • 直接使用First(),Where()就行了,它们是C#的标准,不需要再封装在另一个Search()函数中

标签: c# collections func


【解决方案1】:

使用Where 而不是FirstOrDefault

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

【讨论】:

    【解决方案2】:

    使用 Where 方法而不是 FirstOrDefault

    【讨论】:

      猜你喜欢
      • 2019-08-21
      • 2011-05-13
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多