【问题标题】:Store Linq function into Variable & define on the fly?将 Linq 函数存储到变量中并动态定义?
【发布时间】:2020-02-23 04:56:46
【问题描述】:

我有一个这样的 Linq 查询

var results= StudentsList.GroupBy(x=> x.GroupID)
    .GroupBy(x=> x.Any(g=>g.IsQualified== true))
    .Select(g=> g)
    .ToList();

我想将x.Any(g=>g.IsQualified== true) 部分存储到一个变量中,以便我可以根据我的要求即时更改它(例如:x.Any(g=>g.StudentName== "John")),而无需单独定义新的 Linq 查询。这可能吗?

伪代码

static void SomeFunction(Func<int, int> op)
  {
        var results= StudentsList.GroupBy(x=> x.GroupID)
            .GroupBy(x=> op))
            .Select(g=> g)
            .ToList();
  }

并称它为:

SomeFunction(x => x.Any(g=>g.IsQualified== true));
SomeFunction(x => x.Any(g=>g.StudentName== "John"));
SomeFunction(x => x.Any(g=>g.Country== "USA"));

【问题讨论】:

  • 你想要一个Func&lt;IGrouping&lt;int, Student&gt;, bool&gt;,我假设GroupIDintStudentListStudent 对象的集合,你总是想要第二个分组在bool 值上。并像GroupBy(op) 一样使用它。想想如果它总是x =&gt; x.Any(...),你可能想传入Any的谓词。
  • 看一下 GroupBy 函数的方法签名,只要让你的 SomeFunction 取到准确的时间。如果您使用的是 IQueryable,则为 Expression&lt;Func&lt;TSource,TKey&gt;&gt;;如果您使用的是 IEnumerable,则为 Func&lt;TSource,TKey&gt;

标签: c# linq group-by delegates


【解决方案1】:

Demo on dotnet fiddle

解决方案 1

你可以使用Func&lt;StudentInfo, bool&gt;来实现。

private static IEnumerable<IGrouping<int, StudentInfo>>  SomeFunction(List<StudentInfo> list, Func<StudentInfo, bool> selector)
{
    return list.GroupBy(x => x.GroupID)
                              .Where(g => g.Any(selector) )
                              .Select(g => g);
}

怎么用?

var result1 = SomeFunction(StudentsList, p => p.IsQualified == true);
var result2 = SomeFunction(StudentsList, p => p.Student == "Adam");

解决方案 2(创建扩展方法)

public static IEnumerable<IGrouping<int, StudentInfo>> ExtensionMethod_SomeFunction(this IEnumerable<StudentInfo> list, Func<StudentInfo, bool> selector) 
{
    return list.GroupBy(x => x.GroupID)
                              .Where(g => g.Any(selector) )
                              .Select(g => g);
}

怎么用?

var result3 = StudentsList.ExtensionMethod_SomeFunction(p => p.IsQualified == true);
var result4 = StudentsList.ExtensionMethod_SomeFunction(p => p.Student == "John");

【讨论】:

猜你喜欢
  • 2018-02-15
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多