二、排序Product

1.按名称对产品进行排序,以特定顺序显示一个列表的最简单方式就是先将列表排序,再遍历并显示其中的项。

C#1.1 使用IComparer对ArrayList进行排序

product类

 using System.Collections;
using System.ComponentModel; namespace Chapter01.CSharp1
{
[Description("Listing 1.01")]
public class Product
{
string name;
public string Name
{
get { return name; }
} decimal price;
public decimal Price
{
get { return price; }
} public Product(string name, decimal price)
{
this.name = name;
this.price = price;
} public static ArrayList GetSampleProducts()
{
ArrayList list = new ArrayList();
list.Add(new Product("West Side Story", 9.99m));
list.Add(new Product("Assassins", 14.99m));
list.Add(new Product("Frogs", 13.99m));
list.Add(new Product("Sweeney Todd", 10.99m));
return list;
} public override string ToString()
{
return string.Format("{0}: {1}", name, price);
}
}
}

ArrayListSort类

 using System;
using System.Collections;
using System.ComponentModel; namespace Chapter01.CSharp1
{
[Description("Listing 1.05")]
class ArrayListSort
{
class ProductNameComparer : IComparer
{
public int Compare(object x, object y)
{
Product first = (Product)x;
Product second = (Product)y;
return first.Name.CompareTo(second.Name);
}
} static void Main()
{
ArrayList products = Product.GetSampleProducts();
products.Sort(new ProductNameComparer());
foreach (Product product in products)
{
Console.WriteLine(product);
}
}
}
}

提供一个IComparer实现,比较器。或者Product类实现IComparable。

区别:IComparer和IComparable(比较器接口和可比较的接口)

缺陷:Compare方法中显示强制类型转换,而ArrayList是类型不安全的,转换为对象Product时可能报错。foreach循环中隐式的编译器自动类型转换,转换为Product类型执行时可能报错。

2.C#2.0 引入泛型,使用IComparer<Product>对List<Product>进行排序

product类

 using System.Collections.Generic;
using System.ComponentModel; namespace Chapter01.CSharp2
{
[Description("Listing 1.02")]
public class Product
{
string name;
public string Name
{
get { return name; }
private set { name = value; }
} decimal price;
public decimal Price
{
get { return price; }
private set { price = value; }
} public Product(string name, decimal price)
{
Name = name;
Price = price;
} public static List<Product> GetSampleProducts()
{
List<Product> list = new List<Product>();
list.Add(new Product("West Side Story", 9.99m));
list.Add(new Product("Assassins", 14.99m));
list.Add(new Product("Frogs", 13.99m));
list.Add(new Product("Sweeney Todd", 10.99m));
return list;
} public override string ToString()
{
return string.Format("{0}: {1}", name, price);
}
}
}

ListSortWithComparer类

 using System;
using System.Collections.Generic;
using System.ComponentModel; namespace Chapter01.CSharp2
{
[Description("Listing 1.06")]
class ListSortWithComparer
{
class ProductNameComparer : IComparer<Product>
{
public int Compare(Product first, Product second)
{
return first.Name.CompareTo(second.Name);
}
} static void Main()
{
List<Product> products = Product.GetSampleProducts();
products.Sort(new ProductNameComparer());
foreach (Product product in products)
{
Console.WriteLine(product);
}
}
}
}

使用Comparison<Product>对List<Product>进行排序(C#2),不需要实现ProductNameComparer比较器类型,只是创建一个委托实例(C#2.0 匿名方法)。

 using System;
using System.Collections.Generic;
using System.ComponentModel; namespace Chapter01.CSharp2
{
[Description("Listing 1.07")]
class ListSortWithComparisonDelegate
{
static void Main()
{
List<Product> products = Product.GetSampleProducts();
products.Sort(delegate(Product first, Product second)
{ return first.Name.CompareTo(second.Name); }
);
foreach (Product product in products)
{
Console.WriteLine(product);
}
}
}
}

3.C#3.0 Lambda表达式 在Lambda表达式中使用Comparison<Product>进行排序(C#3)

product类

 using System.Collections.Generic;
using System.ComponentModel; namespace Chapter01.CSharp3
{
[Description("Listing 1.3")]
class Product
{
public string Name { get; private set; }
public decimal Price { get; private set; } public Product(string name, decimal price)
{
Name = name;
Price = price;
} Product()
{
} public static List<Product> GetSampleProducts()
{
return new List<Product>
{
new Product { Name="West Side Story", Price = 9.99m },
new Product { Name="Assassins", Price=14.99m },
new Product { Name="Frogs", Price=13.99m },
new Product { Name="Sweeney Todd", Price=10.99m}
};
} public override string ToString()
{
return string.Format("{0}: {1}", Name, Price);
}
}
}

ListSortWithLambdaExpression类

 using System;
using System.Collections.Generic;
using System.ComponentModel; namespace Chapter01.CSharp3
{
[Description("Listing 1.08")]
class ListSortWithLambdaExpression
{
static void Main()
{
List<Product> products = Product.GetSampleProducts();
products.Sort(
(first, second) => first.Name.CompareTo(second.Name)
);
foreach (Product product in products)
{
Console.WriteLine(product);
}
}
}
}

ListOrderWithExtensionMethod类 使用扩展方法对List<Product>进行排序

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; namespace Chapter01.CSharp3
{
[Description("Listing 1.09")]
class ListOrderWithExtensionMethod
{
static void Main()
{
List<Product> products = Product.GetSampleProducts(); foreach (Product product in products.OrderBy(p => p.Name))
{
Console.WriteLine(product);
}
}
}
}

总结:

→C#1,弱类型的比较功能不支持委托排序。

→C#2,强类型的比较功能,委托比较,匿名方法。

→C#3Lambda表达式,扩展方法,允许列表保持未排序状态。

C#语言各个版本特性(二)的更多相关文章

  1. 为什么说JAVA中要慎重使用继承 C# 语言历史版本特性(C# 1.0到C# 8.0汇总) SQL Server事务 事务日志 SQL Server 锁详解 软件架构之 23种设计模式 Oracle与Sqlserver:Order by NULL值介绍 asp.net MVC漏油配置总结

    为什么说JAVA中要慎重使用继承   这篇文章的主题并非鼓励不使用继承,而是仅从使用继承带来的问题出发,讨论继承机制不太好的地方,从而在使用时慎重选择,避开可能遇到的坑. JAVA中使用到继承就会有两 ...

  2. C# 语言历史版本特性(C# 1.0到C# 7.1汇总更新) C#各版本新特性 C#版本和.NET版本以及VS版本的对应关系

    C# 语言历史版本特性(C# 1.0到C# 7.1汇总更新) 2017年08月06日 11:53:13 阅读数:6705 历史版本 C#作为微软2000年以后.NET平台开发的当家语言,发展至今具有1 ...

  3. C# 语言历史版本特性(C# 1.0到C# 8.0汇总)

    历史版本 C#作为微软2000年以后.NET平台开发的当家语言,发展至今具有17年的历史,语言本身具有丰富的特性,微软对其更新支持也十分支持.微软将C#提交给标准组织ECMA,C# 5.0目前是ECM ...

  4. C# 语言历史版本特性(C# 1.0到C# 7.1汇总更新)

    历史版本C#作为微软2000年以后.NET平台开发的当家语言,发展至今具有17年的历史,语言本身具有丰富的特性,微软对其更新支持也十分支持.微软将C#提交给标准组织ECMA,C# 5.0目前是ECMA ...

  5. [转]C# 语言历史版本特性(C# 1.0到C# 8.0汇总)

    历史版本 C#作为微软2000年以后.NET平台开发的当家语言,发展至今具有17年的历史,语言本身具有丰富的特性,微软对其更新支持也十分支持.微软将C#提交给标准组织ECMA,C# 5.0目前是ECM ...

  6. C#语言各个版本特性(一)

    一.c#版本中添加的功能: C#2.0 泛型 部分类型 匿名方法 迭代器 可空类型 Getter / setter单独可访问性 方法组转换(代表) Co- and Contra-variance fo ...

  7. C#语言各个版本特性(三)

    三.查询集合 1.找出List<Product>列表中符合特定条件的所有元素 C#1.1 查询步骤:循环,if判断,打印 product类 using System.Collections ...

  8. 大数据笔记(二十六)——Scala语言的高级特性

    ===================== Scala语言的高级特性 ========================一.Scala的集合 1.可变集合mutable 不可变集合immutable / ...

  9. Java14版本特性【一文了解】

    「MoreThanJava」 宣扬的是 「学习,不止 CODE」,本系列 Java 基础教程是自己在结合各方面的知识之后,对 Java 基础的一个总回顾,旨在 「帮助新朋友快速高质量的学习」. 当然 ...

随机推荐

  1. Python 中的属性访问与描述符

    在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个name属性,那便可以使用foo.name对此属性进行访问.一般而言,点(. ...

  2. solr跨core查询

    参考文档:这里的跨core不使用solrcloud http://wiki.apache.org/solr/CoreAdmin 注意:跨core查询功能相比单core查询,是有限制的   只需要在ur ...

  3. windows中dos命令指南

    CMD命令:开始->运行->键入cmd或command(在命令行里可以看到系统版本.文件系统版本)chcp 修改默认字符集chcp 936默认中文chcp 650011. appwiz.c ...

  4. uwsgi配置文件的一些细节,uwsgi错误invalid request block size

    [uwsgi] #socket = #这种是使用代理方式访问的,不能直接输入端口访问,要搭配其他的HTTP服务比如NGINX,设置反向代理 http =: #这种是直接可以输入IP端口访问 modul ...

  5. SAFEARRAY

    SAFEARRAY SafeArrayCreate  SafeArrayDestroy // Specify the bounds: // -- dim. count = 2 // -- elemen ...

  6. 可视化库-Matplotlib-Pandas与sklearn结合(第四天)

    1. 计算每一种的比例的百分比 import pandas as pd from matplotlib.ticker import FuncFormatter np.random.seed(0) df ...

  7. Linux CPU 100%, kill -9 杀不掉进程

    1: top 查看 >top -c 此时 我们使用kill -9 15003, 杀掉这个进程短暂的CPU降低几秒, 然后死灰复燃了, 又一个进程占了CPU 99% 2: 查看15003 进程状态 ...

  8. java编写binder服务实例

    文件目录结果如下: 一. 编写AIDL文件 IHelloService.aidl: /** {@hide} */ interface IHelloService { void sayhello(); ...

  9. String和CharSequence

    String 是java中的字符串,它继承于CharSequence. String类所包含的API接口非常多.为了便于今后的使用,我对String的API进行了分类,并都给出的演示程序. Strin ...

  10. oracle 求班级平均分

    select * from ( selectclass 班级,subject,avg(grade) avg_gradefrom student_score group by class,subject ...