将Linq函数存储到Variable&即时定义? [英] Store Linq function into Variable & define on the fly?
本文介绍了将Linq函数存储到Variable&即时定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的Linq查询
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();
我想将零件x.Any(g=>g.IsQualified== true)
存储到一个变量中,以便我可以根据自己的需要即时更改它(例如:x.Any(g=>g.StudentName== "John")
),而无需单独定义新的Linq查询.有可能吗?
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?
伪代码
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"));
推荐答案
解决方案1
您可以使用Func<StudentInfo, bool>
来实现.
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 (创建扩展方法)
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);
}
如何使用它?
var result3 = StudentsList.ExtensionMethod_SomeFunction(p => p.IsQualified == true);
var result4 = StudentsList.ExtensionMethod_SomeFunction(p => p.Student == "John");
这篇关于将Linq函数存储到Variable&即时定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文