问题
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