• 注册
当前位置:1313e > 默认分类 >正文

在C#中使用List编程

                                    在C#中使用List编程

原文地址http://www.c-sharpcorner.com/Ebooks/Download.aspx?eId=61

简介

   泛型是元素的集合,可以通过其索引和提供的功能来进行检索,排序,操作泛型中的项目。

   List类是定义在命名空间System.Collections.Generic下的一个通用类,其可以以任何数据类型来创建一个泛型。在你在你的代码中使用泛型类之前,你必须引入以如下的方式引入命名空间。

using System.Collections.Generic;

 

创建一个泛型

泛型类的构造函数需要一个关键的数据类型。这个数据类型可以是.net中的任何数据类型。

下面的代码段创建了一个字符泛型。

List<string> AuthorList = new List<string>();

 

下面的代码段向该泛型中添加元素。

AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");

另外,我们可以使用对象数组来创建泛型对象。下面的代码将向你展示使用字符串数组来创建一个泛型对象。

// Create a List using Rangestring[] authors = { "Mike Gold", "Don Box","Sundar Lal", "Neel Beniwal" };List<string> authorsRange = new List<string>(authors);

  下面的代码使用整型创建了一个泛型。

List<int> AgeList = new List<int>();

      以下的代码向其中添加元素。

AgeList.Add(35);AgeList.Add(25);AgeList.Add(29);AgeList.Add(21);AgeList.Add(84);

 我们也能够限制泛型的大小。下面的代码将创建一个浮点型泛型,并限制他的大小,它只能包含3个元素。

List<float> PriceList = new List<float>(3);

下面的代码将向这个集合中添加元素。

PriceList.Add(3.25f);PriceList.Add(2.76f);PriceList.Add(1.15f);

创建对象泛型

泛型类能够用来创建任何类型的泛型,包括类。在这篇文章里,你奖看到创建一个带有若干属性的类泛型。

我们在下面首先定义一个名为Author的类,其中含有5个公有属性,其中包括字符串类型的Name, Age, BookTitle,波尔类型的mvp,日期类型的PublishedDate。

public class Author{private string name;private short age;private string title;private bool mvp;private DateTime pubdate;public Author(string name, short age, string title, bool mvp, DateTime pubdate){this.name = name;this.age = age;this.title = title;this.mvp = mvp;this.pubdate = pubdate;}public string Name{get { return name; }set { name = value; }}public short Age{get { return age; }set { age = value; }}public string BookTitle{get { return title; }set { title = value; }}public bool IsMVP{get { return mvp; }set { mvp = value; }}public DateTime PublishedDate{get { return pubdate; }set { pubdate = value; }}}

 

下面的代码中将创建一个Author泛型。

List AuthorList = new List();

 

下面的代码中将创建Author实例,并将其添加到Author泛型中

AuthorList.Add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003,7,10)));AuthorList.Add(new Author("Neel Beniwal", 18, "Graphics Development with C#", false, new DateTime(2010, 2, 22)));AuthorList.Add(new Author("Praveen Kumar", 28, "Mastering WCF", true, new DateTime(2012, 01, 01)));AuthorList.Add(new Author("Mahesh Chand", 35, "Graphics Programming with GDI+", true, new DateTime(2008, 01, 20)));AuthorList.Add(new Author("Raj Kumar", 30, "Building Creative Systems", false, new DateTime(2011, 6, 3)));

 

下面的代码中将遍历这个泛型,输出每个Author对象中的成员。

foreach (var author in AuthorList){Console.WriteLine("Author: {0},{1},{2},{3},{4}", author.Name, author.Age, author.BookTitle, author.IsMVP, author.PublishedDate);}

 

读泛型中的元素

泛型是集合类。我们能够使用foreach来循环遍历其中的所有元素。下面的代码读取所有的项目,并将其逐个通过控制台输出。

foreach (string author in AuthorList){Console.WriteLine(author);}

 

我们能够使用var来遍历热河数据类型。

foreach (var author in AuthorList){Console.WriteLine(author);}

 

下面的代码将创建一个泛型,并读取其中所有元素输出到控制台。

public void CreateList(){// Create a list of strings

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Read all data

Console.WriteLine("Authors List");foreach (var author in AuthorList){Console.WriteLine(author);}}

 

泛型属性

泛型具有三个属性Capacity, Count, and Item

Capacity

Capacity属性能够设置及获得这个集合的容纳量。Capacity值总是大于或者等于Count值。

下面的代码中将创建一个author泛型,并显示其初始的capacity值,然后程序将调用TrimExcess设置capacity。然后将capacity设置为20.

// Create a list of strings

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Original Capacity

Console.WriteLine("Original Capacity: {0}", AuthorList.Capacity);// Trim excess

AuthorList.TrimExcess();Console.WriteLine("Trimmed Capacity: {0}", AuthorList.Capacity);// Update Capacity

AuthorList.Capacity = 20;Console.WriteLine(AuthorList.Capacity);Console.WriteLine("Updated Capacity: {0}", AuthorList.Capacity);

 

Count

Count属性将获得这个泛型中的实际元素的数目。

下面的代码将展示显示一个泛型中元素的数目。

// Create a list of strings

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Count

Console.WriteLine("Count: {0}", AuthorList.Count);

 

Item

Item属性设置获取指定索引的关联值。

下面的代码将设置泛型中第一个元素的值。

// Set Item value

AuthorList["Mahesh Chand"] = 20;// Get Item value

Int16 age = Convert.ToInt16(AuthorList["Mahesh Chand"]);// Create a list of strings

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Get first item of a Liststring auth = AuthorList[0];Console.WriteLine(auth);// Set first item of a List

AuthorList[0] = "New Author";

 

属性方法

泛型类是通用的集合,其提供了所有公用的方法用来增加,删除,查找,替换集合中的 元素。

Add Items

增加方法增加一个元素到泛型中。下面将向你展示使用Add方法向泛型中增加元素。

// Create a list

List<string> AuthorList = new List<string>();// Add items using Add method

AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");AddRange方法用来将一个集合中的元素添加到泛型中。下面的代码将向你展示该方法的使用。// Add a range of itemsstring[] authors = { "Mike Gold", "Don Box","Sundar Lal", "Neel Beniwal" };AuthorList.AddRange(authors);Insert ItemsInsert方法能够 将一个元素插入到泛型的特定位置。下面的代码中将首先创建一个泛型,然后使用Insert方法向其中插入元素。// Create a list

List<string> AuthorList = new List<string>();// Add items using Add method

AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Insert an item at position 2

AuthorList.Insert(1, "Second Author");

 

AddRange方法可以将一个集合中的元素插入到泛型中。下面的代码将展示如果使用AddRange方法方法。

// Insert a range of itemsstring[] authors = { "Mike Gold", "Don Box","Sundar Lal", "Neel Beniwal" };AuthorList.InsertRange(4, authors);

 

Remove Items

Remove方法移除一个泛型中的第一次出现特定元素。Remove方法需要一个元素作为其参数。下面将展示如何使用该方法。

// Create a list of strings

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");AuthorList.Remove("Mahesh Chand");

 

RemoveAt方法移除从0开始的指定索引。下面的代码将删除集合中索引为2的元素。

AuthorList.RemoveRange(3, 2);

 

Clear方法将删除泛型中的所有元素。下面的代码将展示其用法。

AuthorList.Clear();

 

Searching

BinarySearch方法使用二进制搜索算法在排序的集合中搜索指定项目。

// Create a list of strings

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");int itemPosition = AuthorList.BinarySearch("Raj Kumar");Console.WriteLine("Item found at position: {0}", itemPosition + 1);

 

Sorting

Sorting方法排序泛型中的所有项目。下面的代码将向你展示创建一个泛型,并对其进行排序。

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Read all data

Console.WriteLine("Original Authors List");foreach (var author in AuthorList){Console.WriteLine(author);}AuthorList.Sort();Console.WriteLine("Sorted Authors List");foreach (var author in AuthorList){Console.WriteLine(author);}

 

Reverse

Reverse方法将反向泛型中的项目。下面的代码将首先创建一个泛型,然后将其反向。

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Read all data

Console.WriteLine("Original Authors List");foreach (var author in AuthorList){Console.WriteLine(author);}AuthorList.Reverse();Console.WriteLine("Reversed Authors List");foreach (var author in AuthorList){Console.WriteLine(author);}

 

Copy a List

CopyTo方法将复制泛型到一个一维数组中。其有三种形式的重载。

下面将向你展示其用法。

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Dinesh Beniwal");// Create an array of stringsstring[] authorArray = new string[15];// Copy entire List

AuthorList.CopyTo(authorArray);// Copy items starting at index = 4

AuthorList.CopyTo(authorArray, 4);// Copy 4 items starting at index 2 in List and copying// to array starting at index 10

AuthorList.CopyTo(2, authorArray, 3, 4);foreach (string author in authorArray){Console.WriteLine(author);}

 

Find an Item

Contains方法将查找特定的元素是否存在于泛型中。下面的代码将向你展示其用法。

if (AuthorList.Contains("Mahesh Chand"))AuthorList.Remove("Mahesh Chand");

 

IndexOf方法将返回指定元素的第一个索引值。

int idx = AuthorList.IndexOf("Nipun Tomar");

 

LastIndexOf方法将返回指定元素的最后一个索引值。

idx = AuthorList.LastIndexOf("Mahesh Chand");

 

     下面的代码将向你展示这些方法的用法。

List<string> AuthorList = new List<string>();AuthorList.Add("Mahesh Chand");AuthorList.Add("Praveen Kumar");AuthorList.Add("Raj Kumar");AuthorList.Add("Nipun Tomar");AuthorList.Add("Mahesh Chand");AuthorList.Add("Dinesh Beniwal");// Contains - Check if an item is in the listif (AuthorList.Contains("Mahesh Chand")){Console.WriteLine("Author found!");}// Find an item and replace it with new itemint idx = AuthorList.IndexOf("Nipun Tomar");if (idx >= 0){AuthorList[idx] = "New Author";}Console.WriteLine("\nIndexOf ");foreach (var author in AuthorList){Console.WriteLine(author);}// Find Last index of

idx = AuthorList.LastIndexOf("Mahesh Chand");if (idx >= 0){AuthorList[idx] = "New Mahesh";}Console.WriteLine("\nLastIndexOf ");foreach (var author in AuthorList){Console.WriteLine(author);}

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/SuperChan/p/3532371.html

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录