LinQ中提供了很多集合的扩展方法,配合lambda能简化数据处理
C#
int[] ints = { 1, 2, 3, 50, 486, 15, 18, 59, 76, 13, 48, 64, 17 };
IEnumerable<int> inst = ints.Where(i => i > 10);
foreach (int item in inst)
{
Console.WriteLine(item);
}
Where方法会遍历集合中的每个元素,对于每个元素都调用 i = > i > 10 这个表达式判断一下是否为true,如果为true,则把这个放到返回的集合中
自己写一个Where方法
C#
static IEnumerable<int> Mywhere(IEnumerable<int> x,Func<int,bool> f)
{
List<int> result = new List<int>();
foreach (int i in x)
{
if (f(i))
{
result.Add(i);
/* yield return;*/
}
}
return result;
}
Var 可以使用Var让编译器的”类型推断”来简化类型的声明
C#中的Var和JS中的Var不同,仍然是强类型。
*C#中的弱类型是dynamic