举例:
这段代码的逻辑是:
-
从女性模特列表中筛选出颜值大于 80 且等级为普通模特的女性模特。
-
对于每一个符合条件的女性模特,从男性模特列表中筛选出颜值大于 75、等级为普通模特、且年龄比女性模特大但不超过 5 岁的男性模特。
-
将符合条件的女性模特和男性模特组合成一个匿名对象。
-
按照女性模特和男性模特的颜值总和进行降序排序。
-
将最终结果转换为列表。
List<模特> 公司旗下所有模特 = new List<模特>();
var gg = 公司旗下所有模特
.Where(a => a.性别 == 性别.女 && a.等级 == 等级.普通模特 && a.颜值 > 80)
.SelectMany(a => 公司旗下所有模特
.Where(b => b.性别 == 性别.男 && b.等级 == 等级.普通模特 && b.颜值 > 75 && b.年龄 > a.年龄 && b.年龄 < a.年龄 + 5)
.Select(b => new { a, b }))
.OrderByDescending(pair => pair.a.颜值 + pair.b.颜值);
var gl = gg.ToList();
List<模特> 男性模特列表 = // ... 初始化列表
List<模特> 女性模特列表 = // ... 初始化列表
var gl = 女性模特列表
.Where(a => a.颜值 > 80 && a.等级 == 等级.普通模特) // 筛选女性模特
.SelectMany(a => 男性模特列表
.Where(b => b.颜值 > 75 && b.等级 == 等级.普通模特 && b.年龄 > a.年龄 && b.年龄 < a.年龄 + 5) // 筛选符合条件的男性模特
.Select(b => new { a, b }) // 组合成匿名对象
)
.OrderByDescending(pair => pair.a.颜值 + pair.b.颜值) // 按颜值总和降序排序
.ToList();
如果用linq:
List<模特> 公司旗下所有模特 = new List<模特>(); var gg = from ain 公司旗下所有模特from b in 公司旗下所有模特 where a.性别 == 性别.女 where b.性别 ==性别.男 where a.等级 == 等级.普通模特 where b.等级 ==等级.普通模特 where b.年龄>a.年龄 && b.年龄<a.年龄+5 where a.颜值>80 where b.颜值>75 orderby a.颜值+ b.颜值 descending select new { a, b }; var gl = gg.ToList();
“Lambda 表达式”是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。
使用Lambda表达式和LINQ扩展方法
LINQ扩展方法是一组在System.Linq.Enumerable
类中定义的方法,它们可以作为静态方法被调用,并且通常与Lambda表达式一起使用来定义查询逻辑。
List<Circle> circles = ents.Where(x => x is Circle).Cast<Circle>().ToList(); |
然而,正如之前提到的,直接使用OfType<Circle>()
是更简洁且类型安全的方法,因为它结合了Where
和Cast
的功能:
List<Circle> circles = ents.OfType<Circle>().ToList(); |
使用LINQ查询语法
LINQ查询语法是一种声明性查询语法,它使用类似于SQL的语法来定义查询。它通常用于查询表达式(IEnumerable<T>
、IQueryable<T>
等)上的操作,并且可以被编译为等效的LINQ扩展方法调用。
List<Circle> circles = (from e in ents | |
where e is Circle | |
select (Circle)e).ToList(); |
实例如下:
代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
delegate bool D();
delegate bool D2(int i);
class Test
{
D del;
D2 del2;
public void TestMethod(int input)
{
int j = 0;
// Initialize the delegates with lambda expressions.
// Note access to 2 outer variables.
// del will be invoked within this method.
del = () => { j = 10; return j > input; };
// del2 will be invoked after TestMethod goes out of scope.
del2 = (x) => { return x == j; };
// Demonstrate value of j:
// Output: j = 0
// The delegate has not been invoked yet.
Console.WriteLine("调用前j = {0}", j);
// Invoke the delegate.
bool boolResult = del();
// Output: j = 10 b = True
Console.WriteLine("调用后j = {0}. b = {1}", j, boolResult);
}
static void Main()
{
Test test = new Test();
test.TestMethod(5);
// Prove that del2 still has a copy of
// local variable j from TestMethod.
bool result = test.del2(10);
// Output: True
Console.WriteLine(result);
Console.ReadKey();
}
}
}