在C系列语言中,for循环扮演着重要的角色。很难想象,一百行C代码里面没有一个for循环(我有个朋友,写了个几千行的算法,没有用的for循环,我当时很惊讶),就好比,一百行中文里面,没有一个"的"。可见,for循环是代码的基本构造块。由于for循环,一般是用来,对一串类型相同的对象进行操作的,从侧面可以看出,它经常伴随着"数组"而来的。用比较通俗的话说,"for循环"与"数组"是黄金搭档。

在C#里面,引进了foreach循环,它与for循环本质是相同的,由于在foreach循环中,省去了指标i(常常,只用来取第i个项,别无他用),很多人欣然接受了foreach循环,毕竟没有夺走for循环,它还在!
    编程语言一直在进化,先后经历了:...-汇编语言-...-过程式语言-...-面向对象语言-...。总体来说,越来越高级,越来越抽象。当代程序员可以不知道硬件是啥就可以编程;调用一个sort方法就排序了,不知道用的是"冒泡"还是"快速"排序算法(外国人都帮我们弄好了!每当认识到"差距超过20年"这个事实,我都...,好了,不想伤心事了!)。

在C# 3.0中,引进了Extension Methods,伴随而来的是一个新玩意儿Linq。用实用工具Reflector.exe打开System.Core.dll中的System.Linq命名空间,有个Enumerable静态类,其中有大量的对"数组"操作的扩展方法(你能想到的基本都有,不信就去看看!)。

对于用惯了for循环的朋友,如果要他/她停止使用,肯定会觉得日子没法过了。放心好了,我不会劝他/她停止使用的,就像戒烟一样,都是自己的事。(又一次跑题,言归正传!

下面我用代码来演示,如何用"扩展方法/Linq"来干掉"for循环":

[Test]
public void OldSum()
{
int sum0 = 0;
for (int i = 0; i < 10; i++)
{
sum0 += i;
}
Assert.AreEqual(45, sum0);
}

[Test]
public void NewSum()
{
int sum1 = Enumerable.Range(0, 10).Sum();
int sum2 = Enumerable.Range(0, 10).Aggregate((x, y) => x + y);
int sum3 = Enumerable.Range(0, 10).Aggregate(0, (x, y) => x + y);

Assert.AreEqual(45, sum1);
Assert.AreEqual(45, sum2);
Assert.AreEqual(45, sum3);
}

注:无论是对一串数字求和还是求积,归根到底,都是把一串东西变成一个东西,此时就用Aggregate

[Test]
public void OldFilter()
{
int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> odd_list = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] % 2 == 1)
{
odd_list.Add(arr[i]);
}
}
int[] odd_arr = odd_list.ToArray();
Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));
}

[Test]
public void NewFilter()
{
int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] odd_arr = arr.Where(x => x % 2 == 1).ToArray();
Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));
}

注:无论是取奇数还是偶数,归根到底,都是取一串东西中的某些东西,此时就用Where

[Test]
public void OldMap()
{
int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> new_list = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
new_list.Add(arr[i] * 10);
}
int[] new_arr = new_list.ToArray();
Assert.That(new_arr, Is.EquivalentTo(new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }));
}

[Test]
public void NewMap()
{
int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] new_arr = arr.Select(x => x * 10).ToArray();
Assert.That(new_arr, Is.EquivalentTo(new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }));
}

注:无论是x10还是+99,归根到底,都是把一串东西变成一串新东西,此时就用Select

[Test]
public void PrintMultiplicationFact()
{

Console.Write(
" 1 x 1= 1 \n"
+ " 1 x 2= 2 2 x 2= 4 \n"
+ " 1 x 3= 3 2 x 3= 6 3 x 3= 9 \n"
+ " 1 x 4= 4 2 x 4= 8 3 x 4=12 4 x 4=16 \n"
+ " 1 x 5= 5 2 x 5=10 3 x 5=15 4 x 5=20 5 x 5=25 \n"
+ " 1 x 6= 6 2 x 6=12 3 x 6=18 4 x 6=24 5 x 6=30 6 x 6=36 \n"
+ " 1 x 7= 7 2 x 7=14 3 x 7=21 4 x 7=28 5 x 7=35 6 x 7=42 7 x 7=49 \n"
+ " 1 x 8= 8 2 x 8=16 3 x 8=24 4 x 8=32 5 x 8=40 6 x 8=48 7 x 8=56 8 x 8=64 \n"
+ " 1 x 9= 9 2 x 9=18 3 x 9=27 4 x 9=36 5 x 9=45 6 x 9=54 7 x 9=63 8 x 9=72 9 x 9=81 \n"
);

/*********************方法一: 嵌套循环*************************/
for (int j = 1; j < 10; j++)
{
for (int i = 1; i < 10; i++)
{
if (i <= j)
{
Console.Write("{0, 2} x{1, 2}={2, 2}\t", i, j, i * j);
}
}
Console.Write("\n");
}

/*********************方法二: 扩展方法*************************/
Enumerable.Range(1, 9)
.SelectMany(j => Enumerable.Range(1, 9), (j, i) => new { i, j })
.Where(x => x.i <= x.j)
.GroupBy(x => x.j)
.Select(g => g.Aggregate("", (a, x) => a + string.Format("{0, 2} x{1, 2}={2, 2}\t", x.i, x.j, x.i * x.j)))
.ToList().ForEach(x => Console.WriteLine(x));

/*********************方法三: Linq表达式************************/
(
from j in Enumerable.Range(1, 9)
from i in Enumerable.Range(1, 9)
where i <= j
group new { i, j } by j into g
select new
{
LineNo = g.Key,
Line = g.Aggregate("", (a, x) => a + string.Format("{0, 2} x{1, 2}={2, 2}\t", x.i, x.j, x.i * x.j))
}

).ToList().ForEach(g => Console.WriteLine(g.Line));
}

注:对于嵌套的for循环,就用SelectMany

声明:for循环很好,你可以继续用,如果你想用的话。如果你喜欢尝试新东西,我想告诉你:"也许可以试试!"

附录1:乘法口诀

1 x 1= 1
1 x 2= 2 2 x 2= 4
1 x 3= 3 2 x 3= 6 3 x 3= 9
1 x 4= 4 2 x 4= 8 3 x 4=12 4 x 4=16
1 x 5= 5 2 x 5=10 3 x 5=15 4 x 5=20 5 x 5=25
1 x 6= 6 2 x 6=12 3 x 6=18 4 x 6=24 5 x 6=30 6 x 6=36
1 x 7= 7 2 x 7=14 3 x 7=21 4 x 7=28 5 x 7=35 6 x 7=42 7 x 7=49
1 x 8= 8 2 x 8=16 3 x 8=24 4 x 8=32 5 x 8=40 6 x 8=48 7 x 8=56 8 x 8=64
1 x 9= 9 2 x 9=18 3 x 9=27 4 x 9=36 5 x 9=45 6 x 9=54 7 x 9=63 8 x 9=72 9 x 9=81

附录2:完整代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;namespace KSharp
{[TestFixture]public class TestForLoop{[Test]public void OldSum(){int sum0 = 0;for (int i = 0; i < 10; i++){sum0 += i;}Assert.AreEqual(45, sum0);}[Test]public void NewSum(){int sum1 = Enumerable.Range(0, 10).Sum();int sum2 = Enumerable.Range(0, 10).Aggregate((x, y) => x + y);int sum3 = Enumerable.Range(0, 10).Aggregate(0, (x, y) => x + y);Assert.AreEqual(45, sum1);Assert.AreEqual(45, sum2);Assert.AreEqual(45, sum3);}[Test]public void OldFilter(){int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };List<int> odd_list = new List<int>();for (int i = 0; i < arr.Length; i++){if (arr[i] % 2 == 1){odd_list.Add(arr[i]);}}int[] odd_arr = odd_list.ToArray();Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));}[Test]public void NewFilter(){int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };int[] odd_arr = arr.Where(x => x % 2 == 1).ToArray();Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));}[Test]public void OldMap(){int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };List<int> new_list = new List<int>();for (int i = 0; i < arr.Length; i++){new_list.Add(arr[i] * 10);}int[] new_arr = new_list.ToArray();Assert.That(new_arr, Is.EquivalentTo(new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }));}[Test]public void NewMap(){int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };int[] new_arr = arr.Select(x => x * 10).ToArray();Assert.That(new_arr, Is.EquivalentTo(new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }));}[Test]public void PrintMultiplicationFact(){Console.Write(" 1 x 1= 1    \n"+ " 1 x 2= 2     2 x 2= 4    \n"+ " 1 x 3= 3     2 x 3= 6     3 x 3= 9    \n"+ " 1 x 4= 4     2 x 4= 8     3 x 4=12     4 x 4=16    \n"+ " 1 x 5= 5     2 x 5=10     3 x 5=15     4 x 5=20     5 x 5=25    \n"+ " 1 x 6= 6     2 x 6=12     3 x 6=18     4 x 6=24     5 x 6=30     6 x 6=36    \n"+ " 1 x 7= 7     2 x 7=14     3 x 7=21     4 x 7=28     5 x 7=35     6 x 7=42     7 x 7=49    \n"+ " 1 x 8= 8     2 x 8=16     3 x 8=24     4 x 8=32     5 x 8=40     6 x 8=48     7 x 8=56     8 x 8=64    \n"+ " 1 x 9= 9     2 x 9=18     3 x 9=27     4 x 9=36     5 x 9=45     6 x 9=54     7 x 9=63     8 x 9=72     9 x 9=81    \n");/*********************方法一: 嵌套循环*************************/for (int j = 1; j < 10; j++){for (int i = 1; i < 10; i++){if (i <= j){Console.Write("{0, 2} x{1, 2}={2, 2}\t", i, j, i * j);}}Console.Write("\n");}/*********************方法二: 扩展方法*************************/Enumerable.Range(1, 9).SelectMany(j => Enumerable.Range(1, 9), (j, i) => new { i, j }).Where(x => x.i <= x.j).GroupBy(x => x.j).Select(g => g.Aggregate("", (a, x) => a + string.Format("{0, 2} x{1, 2}={2, 2}\t", x.i, x.j, x.i * x.j))).ToList().ForEach(x => Console.WriteLine(x));/*********************方法三: Linq表达式************************/(from j in Enumerable.Range(1, 9)from i in Enumerable.Range(1, 9)where i <= jgroup new { i, j } by j into gselect new{LineNo = g.Key,Line = g.Aggregate("", (a, x) => a + string.Format("{0, 2} x{1, 2}={2, 2}\t", x.i, x.j, x.i * x.j))}).ToList().ForEach(g => Console.WriteLine(g.Line));}}

  

转载于:https://www.cnblogs.com/jizhongfong/p/4498456.html

Linq干掉for循环相关推荐

  1. python简单入门

    一. 初识python. 1. 认识计算机 CPU(大脑) 3GHZ + 内存(DDR4) + 主板 + 电源(心脏)+ 显示器 + 键盘 +鼠标+ 显卡 + 硬盘 80MB/s 操作系统 windo ...

  2. .net npoi xssfclientanchor设置图片缩放大小_.NET导出Excel的四种方法及评测

    前言 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspose.Cells四个市面上常见的库 ...

  3. .NET Core 性能分析: xUnit.Performance 简介

    xunit-performance 是xUnit的一个扩展, 使用它可以对.NET Core项目进行性能测试. 官网:https://github.com/Microsoft/xunit-perfor ...

  4. Visual Studio 2019预览,净生产力

    本文章为机器翻译. https://blogs.msdn.microsoft.com/dotnet/2018/12/13/visual-studio-2019-net-productivity/ 该文 ...

  5. 工作流引擎 Activiti 保姆级教程

    大家好,我是老赵! 一.工作流介绍 1.1 概念 工作流(Workflow),就是通过计算机对业务流程自动化执行管理.它主要解决的是"使在多个参与者之间按照某种预定义的规则自动进行传递文档. ...

  6. python少年_python简单入门

    一. 初识python. 1. 认识计算机 CPU(大脑) 3GHZ + 内存(DDR4) + 主板 + 电源(心脏)+ 显示器 + 键盘 +鼠标+ 显卡 + 硬盘 80MB/s 操作系统 windo ...

  7. 中兴面试总结,华为。技术,市场

    1,软件测试,如何把这个测试做的更好. 进到一个新项目,作为测试人员应该都是想把测试做好,项目在符合客户质量要求的情况下按时交付的吧.但往往都事与愿违,造成这个结果的原因有很多很多.通过这段时间做自动 ...

  8. c# 循环给数组每个元素加个逗号_C#规范整理集合和Linq

    LINQ(Language Integrated Query,语言集成查询)提供了类似于SQL的语法,能对集合进行遍历.筛选和投影.一旦掌握了LINQ,你就会发现在开发中再也离不开它.   开始! 前 ...

  9. linq介绍及工作中应用两例——左联与内联,linq循环方法

    1 linq介绍 1.1 linq产生背景 一个应用服务后台程序,肯定会需要格式各样的数据检索跟操作,而这些数据在过去的这些年里一般都会包含在关系型数据库或者xml文件中. .Net3.5版本发行之前 ...

最新文章

  1. html悬浮的图片居中,HTML/CSS:图片居中(水平居中和垂直居中)
  2. 用python画爱心的代码-怎么用python实现画爱心
  3. kotlin学习之泛型(十四)
  4. LeetCode 94. 二叉树的中序遍历(中序遍历)
  5. 记tcp网络编程中遇到的readline()方法
  6. 《网页设计技巧》系列之一 浅谈文本排版
  7. matlab 支撑集,基于OMP算法的快速压缩感知图像重构
  8. CompoundButton
  9. 火狐浏览器——问题解决:网络正常但无法打开百度页面和搜索功能
  10. ImageJ(Fiji)安装
  11. android 浏览器 该网站的安全证书有问题
  12. 全国大学生信息安全竞赛初赛writeup
  13. 力推个p站相关站点 画师美图和各种工具方法
  14. 【组合数学 】 推广牛顿二项式 ( 牛顿二项式推广 | 推导流程 | 题目解析 )
  15. 第21课 机灵的小老鼠
  16. 计算机组成与体系结构——计算机体系结构分类-Flynn——2020.11.19
  17. 口袋西游150服务器维护,口袋西游版本更新披露 幽冥界场景首曝
  18. 数据库——sql修改主键
  19. 上海大治河二线船闸总体设计与结构计算
  20. 力扣解法汇总661- 图片平滑器

热门文章

  1. 用c语言输出倒直角梯形,编程题(C/C++程序设计,同济大学mooc)
  2. 电气控制基本原理2--两台三相笼型异步电动机的设计
  3. 成都市等2015年《四川省建设工程工程量清单计价定额》人工费调整的批复〔2019〕6号
  4. 电压频率转换电路(集成运放)
  5. 边缘计算Tensorflow Lite
  6. 信息安全数学基础 Chapter 4——二次剩余与方根
  7. 【EHub_tx1_tx2_E100】Ubuntu18.04 + ROS_ Melodic + Velodyne VLP-16雷达 测试使用
  8. java大厂技术面试第八课 nginx/docker/tcp等
  9. 修改dns解析服务器多久生效,域名解析生效时间,域名解析后多久生效 | 帮助信息-动天数据...
  10. mybatis中一级缓存和二级缓存