Aggregate

Aggregate我用的最多的地方就是拼接字符串,打个比方来说,如果有数组,想要的结果是在他们之间插入一个","然后返回拼接以后的新字符串。

常规的做法是:

List<int> intList = new List<int>() { , , , ,  };
Console.WriteLine(string.Join(",", intList));

得到的结果是:

,,,,

但是如果碰到想要的结果是'1','2','3','4','5'这样的字符串后,在用join这个方法就不好搞了。然而用for或者foreach一样可以很简单的 就实现效果了

List<string> strList = new List<string>() {"a","b","c","d","e" };
string tmp = string.Empty;
foreach (string str in strList)
{
tmp += "'" + str + "',";
}
Console.WriteLine(tmp.Trim(','));

但是啊,这样写太土了。现在就可以用Aggregate方法来实现。

 List<string> strList = new List<string>() { "a", "b", "c", "d", "e" };
tmp=strList.ToArray().Aggregate("",(c, i) => c + ("'" + i + "',")).Trim(',');
Console.WriteLine(tmp);

最后得到的结果就是:

'a','b','c','d','e'

Except

Except是求集合之间的差集。直接上代码

 static void Main(string[] args)
{ List<string> strList1 = new List<string>() { "a", "b", "c", "d", "e" }; List<string> strList2 = new List<string>() { "a", "b", "e", "f", "g" };
string tmp = string.Empty; tmp=strList1.Except(strList2).Aggregate("",(i,c)=>i+" "+c);
Console.WriteLine("实例方法调用Except查询strList1不存在strList2中的数据:{0}",tmp); tmp = strList2.Except(strList1).Aggregate("", (i, c) => i + " " + c);
Console.WriteLine("实例方法调用Except查询strList2不存在strList1中的数据:{0}", tmp); tmp = Enumerable.Except(strList1, strList2).Aggregate("", (i, c) => i + " " + c);
Console.WriteLine("Enumerable静态方法调用Except查询strList2不存在strList1中的数据:{0}", tmp);
}

直接结果:

那再来看看这个例子:

执行结果会是什么?张三?

class Program
{
static void Main(string[] args)
{
string tmp = string.Empty; List<Item> objList1 = new List<Item>() { };
objList1.Add(new Item { Key = "a", Name = "张三" });
objList1.Add(new Item { Key = "b", Name = "李四" });
objList1.Add(new Item { Key = "c", Name = "王五" }); List<Item> objList2 = new List<Item>() { };
objList2.Add(new Item { Key = "b", Name = "李四" });
objList2.Add(new Item { Key = "c", Name = "王五" });
objList2.Add(new Item { Key = "d", Name = "赵六" }); tmp = Enumerable.Except(objList1, objList2).Select(item => item.Name).Aggregate("", (i, c) => i + " " + c);
Console.WriteLine("Enumerable静态方法调用Except查询objList1不存在objList2中的数据:{0}", tmp);
}
} public class Item
{
public string Key { get; set; }
public string Name { get; set; }
}

出乎意料的是objList1集合里面的所有数据都显示出来了,这是为啥?原因很简单,因为Item是对象,对象之间的比较不想简单类型那样的“=”来判断的。

所以复杂对象之间的比较需要自定义一个比较器:

 public class ItemComparer : IEqualityComparer<Item>
{
public bool Equals(Item x, Item y)
{ if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//return x.Key == y.Key && x.Name == y.Name;
return x.Key == y.Key;
} public int GetHashCode(Item product)
{
if (Object.ReferenceEquals(product, null)) return ; int hashProductName = product.Key == null ? : product.Key.GetHashCode(); int hashProductCode = product.Name.GetHashCode(); return hashProductName ^ hashProductCode;
}
}

然后Main方法里面Enumerable.Except方法需要加入第三个参数new ItemComparer()

tmp = Enumerable.Except(objList1, objList2,new ItemComparer()).Select(item => item.Name).Aggregate("", (i, c) => i + " " + c);

再来看看执行结果:

这样就对了!

未完....

Linq的一些很方便的方法的更多相关文章

  1. Eclipse解决Ctrl+c很卡的方法

    问题如下 : 每当在eclipse中开发java项目打开jsp页面编辑的时候,按了ctrl+c就会卡死几秒的状态,一天经常这样会让人非常的烦躁. 解决方法如下: Eclipse -- Windows- ...

  2. [转]win7下apache2.4响应很慢解决方法

    win7下apache2.4响应很慢解决方法 PS.按照以下方法测试了以下,似乎确实快了一点[skysowe] 转载自: http://blog.sina.com.cn/s/blog_75ad1010 ...

  3. Repeater为空时显示“暂无数据”,很方便实用方法

    Repeater为空时显示“暂无数据”,很方便实用方法 <FooterTemplate>   <asp:Label ID="lblEmptyZP" Text=&q ...

  4. LINQ学习系列-----1.3 扩展方法

    这篇内容继续接着昨天的Lambda表达式的源码继续下去.昨天讲了Lambda表达式,此篇讲扩展方法,这两点都是Linq带来的新特性.    一.扩展方法介绍   废话不多说,先上源码截图: 上图中Ge ...

  5. Linq中string转int的方法

    Linq中string转int的方法   在做批量删除时,需把一串id值所对应的数据删除,调试出现问题: Linq语句中如果使用ToString()进行类型转换,编译时不会报错,但执行时会出现如下错误 ...

  6. entity framework 删除数据库出现错误的解决方法--最土但是很有效的方法

    无法删除数据库,因为该数据库当前正在使用. public ChinaerContext() : base("name=ContextConn") { // Database.Set ...

  7. Linq 分页不可缺少的两个方法

    //LINQ分页的方法 //1.获取总页数 public int GetPageCount(int pageSize)//pageSize是每页的行数 { //先查出总共有多少行 int rowCou ...

  8. Linq lamda表达式Single和First方法

      让我们来看看如何对一个整数数组使用 Single 操作符.这个整数数组的每个元素代表 2 的 1 到 10 次方.先创建此数组,然后使用 Single 操作符来检索满足 Linq Lambda表达 ...

  9. [MySQL优化案例]系列 — slave延迟很大优化方法

    备注:插图来自网络搜索,如果觉得不当还请及时告知 :) 一般而言,slave相对master延迟较大,其根本原因就是slave上的复制线程没办法真正做到并发.简单说,在master上是并发模式(以In ...

随机推荐

  1. Delphi写的DLL回调C#

    C#的调用Delphi的DLL没有问题,DLL回调时遇到了麻烦,网上找了个方法,解决了这个问题 Delphi部分,列举了三种回调函数定义 library test; uses SysUtils; {$ ...

  2. 自己修改的两个js文件

    sea-base.js /** * Sea.js 2.2.3 | seajs.org/LICENSE.md */ (function(global, undefined) { // Avoid con ...

  3. MyBatis入门学习教程-MyBatis缓存

    一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了 package me.gacl.test; 2 import me.gacl.domain.User; import ...

  4. windows使用nginx实现网站负载均衡测试实例

    如果你关注过nginx,必定知道nginx这个软件有什么用的,如果你的网站访问量越来越高,一台服务器已经没有办法承受流量压力,那就增多几台服务器来做负载吧.做网站负载可以买硬件设备来实现,比如F5,不 ...

  5. linux下XAMP集成开发环境搭建流程总结

    一.安装xampp: 1.用wget下载安装包; 2.为安装包添加执行权限; 3.直接安装到/opt/; 4.添加开机启动:ln -s /opt/lampp/lampp  /usr/bin/ 二.防火 ...

  6. JS toFixed 四舍六入五成双

    以前一直以为toFixed就是四舍五入的方法,后来又有一段时间以为toFixed是五舍六入.今天终于写的时候,终于才知道toFixed是一个叫做四舍六入无成双的诡异的方法... 完全不明白为什么要这么 ...

  7. Dictionary的几种遍历方法

    Dictionary<string, int> list = new Dictionary<string, int>(); list.Add("d", 1) ...

  8. Laravel学习笔记(五)数据库 数据库迁移案例2——创建数据结构,数据表,修改数据结构

    默认假设 所有的列在定义的时候都有默认的假设,你可以根据需要重写. Laravel假定每个表都有一个数值型的主键(通常命名为”id”),确保新加入的每一行都是唯一的.Laravel只有在每个表都有数值 ...

  9. oracle大表添加字段default经验分享

    当oracle单表数据量上亿时,对表进行alter table aa add column_1 varchar2(2) defalut 'Y';时,效率及安全性是必须考虑的因素. 本帖以2亿的数据表a ...

  10. centos 7 + mono + jexus 环境安装

    1.安装 mlocate yum list|grep locate yum install mlocate.x86_64 updatedb 2.安装 yum-utils yum list|grep y ...