将 Linq 函数存储到变量中并即时定义?
Store Linq function into Variable & define on the fly?
我有一个这样的 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"));
解决方案 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 (创建扩展方法)
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 查询
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"));
解决方案 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 (创建扩展方法)
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");