Store Linq function into Variable & define on the fly?

。_饼干妹妹 提交于 2020-03-22 09:04:12

问题


I have a Linq query like this

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

I want to store the part x.Any(g=>g.IsQualified== true) into a variable so that I can change it on the fly (example: x.Any(g=>g.StudentName== "John") ) based on my requirement and without defining a new Linq query separately. Is that possible?

Pseudo Code

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

And call it:

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

回答1:


Demo on dotnet fiddle

Solution 1

You can use Func<StudentInfo, bool> to achieve it.

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);
}

How to use it?

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

Solution 2 (Create Extension method)

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);
}

How to use it?

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


来源:https://stackoverflow.com/questions/60359312/store-linq-function-into-variable-define-on-the-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!