C# List

Following examples show how to create and manipulate with .NET strongly typed list List<T>.

List<T>

List is a generic type, so you can create list of any type (it can be reference type such asCustomer or value type such as int)

var list1 = new List<object>(); var list2 = new List<Customer>(); var list3 = new List<int>();

All the following examples use list of integer values List<int>.

List Constructor

Creates an empty list (of integer values).

var list = new List<int>();
list: (empty)

Creates a list and initializes it with some items (integer values).

var list = new List<int>() { 8, 3, 2 };
list: 8 3 2

Creates a list and initializes it with items of another list (or array or anything which implements IEnumerable interface).

var listA = new List<int>() { 8, 3, 2 };
var listB = new List<int>(listA);
listB: 8 3 2

Creates a list with specified capacity.

var list = new List<int>(16);
list.Count: 0
list.Capacity: 16

List[index]

Gets an item at the specified zero-based index.

list: 8 3 2
int item = list[1];
item: 3

Sets the item at the specified zero-based index.

list: 8 3 2
list[1] = 4;
list: 8 4 2

List.Add

Adds an item to the end of the list.

list: 8 3 2
list.Add(5);
list: 8 3 2 5

List.AddRange

Adds items of another list (or an IEnumerable collection) to the end of the list.

listA: 8 3 2
listB: 5 7
listA.AddRange(listB);
listA: 8 3 2 5 7

List.BinarySearch

Returns the zero-based index of the item in the sorted list. If the items is not found, returns a negative number. See MSDN for more info.

This List<T> method works only if the type T implements IComparable<T> or IComparable interface.

list: 1 3 4 6 7 9
int index = list.BinarySearch(6);
index: 3

This BinarySearch method overload uses specified comparer.

list: 1 3 4 6 7 9
int index = list.BinarySearch(item: 6,comparer: new MyComparer() );
index: 3

This BinarySearch method overload uses specified comparer and search in specified range.

list: 1 3 4 6 7 9
int index = list.BinarySearch(index: 1, count: 3, item: 6,comparer: new MyComparer() );
index: 3

This example shows the case when the item was not found in the list. The result is negative number.

list: 1 3 4 6 7 9
int index = list.BinarySearch(index: 1, count: 2, item: 6,comparer: new MyComparer() );
index: -4
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y) { return x.CompareTo(y); }
}

List.Clear

Removes all items from the list. Count is zero, Capacity is unchanged.

list: 8 3 2
list.Clear();
list: (empty)

List.Contains

Returns true if the list contains the specified item.

list: 8 3 2
bool result = list.Contains(3);
result: true

Returns false if the list doesn't contain the specified item.

list: 8 3 2
bool result = list.Contains(6);
result: false

List.ConvertAll

Converts items using specified delegate. Items can be converted to another type.

listA: 8 3 2
var conv = new Converter<int,decimal>(x => (decimal)(x+1));

var listB = listA.ConvertAll<decimal>(conv);

listB: 9.0 4.0 3.0

List.CopyTo

Copies all list items into the beginning of the specified array.

list: 8 3 2
array: 0 0 0 0 0
list.CopyTo(array);
array: 8 3 2 0 0

Copies all list items into the array, starting from the specified array index.

list: 8 3 2
array: 0 0 0 0 0
list.CopyTo(array, arrayIndex: 2);
array: 0 0 8 3 2

Copies a range of list items into the array, starting from the specified array index.

list: 8 3 2
array: 0 0 0 0 0
list.CopyTo(index: 1, array: array,arrayIndex: 3, count: 1);
array: 0 0 0 3 0

List.Exists

Returns true if the list contains items matching the specified predicate.

list: 8 3 2
bool result = list.Exists(x => x == 3);
result: true

Returns false if the list doesn't contain items matching the specified predicate.

list: 8 3 2
bool result = list.Exists(x => x > 10);
result: false

List.Equals

Returns true if the two specified lists are reference equal (are the same instance).

var listA = new List<int>() { 8, 3, 2 };
var listB = listA;
bool result = listA.Equals(listB);
result: true

Returns false if the specified two lists are not the same instance. To determine whether all items of the two lists are equal use LINQ method SequenceEqual.

var listA = new List<int>() { 8, 3, 2 };
var listB = new List<int>() { 8, 3, 2 };
bool result = listA.Equals(listB);
result: false

List.Find

Returns the first occurrence of item matching the specified predicate.

list: 8 3 2
int item = list.Find(x => x > 2);
item: 3

For List<T> returns the default value of type T if no item matches the predicate. In this case the default value of int is 0.

list: 8 3 2
int item = list.Find(x => x > 10);
item: 0 (default value)

List.FindAll

Returns list with items matching the specified predicate.

listA: 8 3 2
var listB = listA.FindAll(x => x > 2);
listB: 8 3

Returns empty list, if no item matches the specified predicate.

listA: 8 3 2
var listB = listA.FindAll(x => x > 10);
listB: (empty)

List.FindIndex

Returns zero-based index of the first item which matches the specified predicate.

list: 8 3 6 4 2
int index = list.FindIndex(x => x < 5);
index: 1

Returns index of the first item which matches the specified predicate. It searches the list from startIndex to the end of the list.

list: 8 3 6 4 2
int index = list.FindIndex(startIndex: 2, match: x => x < 5);
index: 3

Returns index of the first item which matches the specified predicate. It searches the list in the range specified by startIndex and count.

list: 8 3 6 4 2
int index = list.FindIndex(startIndex: 2, count: 2,match: x => x < 5);
index: 3

Returns -1 if no item matches the specified predicate.

list: 8 3 6 4 2
int index = list.FindIndex(startIndex: 2, count: 2,match: x => x < 3);
index: -1

List.FindLast

Returns the last occurrence of item matching the specified predicate.

list: 8 3 2
int item = list.FindLast(x => x < 5);
item: 2

For List<T> returns the default value of type T if no item matches the predicate. In this case the default value of int is 0.

list: 8 3 2
int item = list.FindLast(x => x > 10);
item: 0 (default value)

List.FindLastIndex

Returns zero-based index of the last item which matches the specified predicate.

list: 2 4 6 3 8
int index = list.FindLastIndex(x => x < 5);
index: 3

Returns index of the last item which matches the specified predicate. It searches the list from the beginning to the specified startIndex.

list: 2 4 6 3 8
int index = list.FindLastIndex(startIndex: 2, match: x => x < 5);
index: 1

Returns index of the last item which matches the specified predicate in the range specified by count and the end index surprisingly called startIndex.

list: 2 4 6 3 8
int index = list.FindLastIndex(startIndex: 2, count: 2,match: x => x < 5);
index: 1

Returns -1 if no item matches the specified predicate.

list: 2 4 6 3 8
int index = list.FindLastIndex(startIndex: 2, count: 2,match: x => x < 3);
index: -1

List.ForEach

Executes the specified action for each item in the list. It does the same as standardC# foreach statement.

list: 8 3 2
list.ForEach(x => {Console.Write(x); });
output: 832

List.GetRange

Returns a list with a range of items of the source list.

listA: 8 3 6 4 2
var listB = listA.GetRange(index: 1, count: 3);
listB: 3 6 4

List.IndexOf

Returns the zero-based index of the first occurrence of the item in the list.

list: 8 3 2 6 8
int index = list.IndexOf(8);
index: 0

Returns the index of the first occurrence of the item in the list. It searches the list from the specified index to the end of the list.

list: 8 3 2 6 8
int index = list.IndexOf(item: 8,index: 1);
index: 4

Returns the index of the first occurrence of the item in the list. It searches the list in the range specified by index and count.

list: 8 3 2 6 8
int index = list.IndexOf(item: 3,index: 1, count: 2);
index: 1

Returns -1 if the item is not found in the specified range.

list: 8 3 2 6 8
int index = list.IndexOf(item: 8,index: 1, count: 2);
index: -1

List.Insert

Inserts an item into the list at the specified index.

list: 8 3 2
list.Insert(index: 1, item: 5);
list: 8 5 3 2

List.InsertRange

Inserts items of another list (or object implementing IEnumerable) into the list at the specified index.

listA: 8 3 2
listB: 5 7
listA.InsertRange(index: 1,collection: listB);
listA: 8 5 7 3 2

List.LastIndexOf

Returns the zero-based index of the last occurrence of the item in the list.

list: 8 3 2 6 8
int index = list.LastIndexOf(8);
index: 4

Returns the index of the last occurrence of the item in the list. It searches the list from the beginning of the list to the specified index.

list: 8 3 2 6 8
int index = list.LastIndexOf(item: 8, index: 3);
index: 0

Returns the index of the last occurrence of the item in the list. It searches in the range specified by count and the end index.

list: 8 3 2 6 8
int index = list.LastIndexOf(item: 6, index: 3, count: 2);
index: 3

Returns -1 if the item is not found in the specified range.

list: 8 3 2 6 8
int index = list.LastIndexOf(item: 8, index: 3, count: 2);
index: -1

List.Remove

Removes the first occurence of the specified item from the list.

list: 8 4 2 4
list.Remove(item: 4);
list: 8 2 4

List.RemoveAll

Removes all items matching the specified predicate.

list: 8 3 6 2
list.RemoveAll(x => x < 4);
list: 8 6

List.RemoveAt

Removes the item at the specified index.

list: 8 3 6 2
list.RemoveAt(index: 2);
list: 8 3 2

List.RemoveRange

Removes items from the specified range.

list: 8 3 6 2 4 5
list.RemoveRange(index: 2,count: 3);
list: 8 3 5

List.Reverse

Reverses the order of all items in the list.

list: 8 3 2
list.Reverse();
list: 2 3 8

Reverses the order of the items in the specified range.

list: 8 3 6 2
list.Reverse(index: 1, count: 2);
list: 8 6 3 2

List.Sort

Sorts all items in the list.

This List<T> method works only if the type T implements IComparable<T> or IComparable interface.

list: 8 3 6 2
list.Sort();
list: 2 3 6 8

Sorts list using comparison delegate.

list: 8 3 6 2
list.Sort((x, y) => x.CompareTo(y));
list: 2 3 6 8

Sorts list using comparison delegate (in descending order).

list: 8 3 6 2
list.Sort((x, y) => y.CompareTo(x));
list: 8 6 3 2

Sorts the list using custom comparer.

list: 8 3 6 2
list.Sort(new MyComparer());
list: 2 3 6 8

Sorts the specified range of the list using custom comparer.

list: 8 3 6 2 4 5
list.Sort(index: 2, count: 3,comparer: new MyComparer());
list: 8 3 2 4 6 5
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y) { return x.CompareTo(y); }
}

List.ToArray

Creates new array and copies all items into it.

list: 8 3 2
int[] array = list.ToArray();
array: 8 3 2

Returns empty array for empty list.

list: (empty)
int[] array = list.ToArray();
array: (empty)

List.TrimExcess

Trims the list capacity to reduce memory usage if it's reasonable. It sets Capacity to the same value as Count but only if the Count is less than about 90 % of Capacity.

list: 1 2 3 4 5
list.Count: 5
list.Capacity: 8
list.TrimExcess();
list.Count: 5
list.Capacity: 5

If the Count is almost the same as the list Capacity it does nothing.

list: 1 2 3 4 5 6 7
list.Count: 7
list.Capacity: 8
list.TrimExcess();
list.Count: 7
list.Capacity: 8

List.TrueForAll

Returns true if all items in the list match the specified predicate.

list: 8 3 2
bool result = list.TrueForAll(x => x < 10);
result: true

Returns false if not all items in the list match the specified predicate.

list: 8 3 2
bool result = list.TrueForAll(x => x < 5);
result: false

C# 完整List例子的更多相关文章

  1. 《Java从入门到失业》第四章:类和对象(4.3):一个完整的例子带你深入类和对象

    4.3一个完整的例子带你深入类和对象 到此为止,我们基本掌握了类和对象的基础知识,并且还学会了String类的基本使用,下面我想用一个实际的小例子,逐步来讨论类和对象的一些其他知识点. 4.3.1需求 ...

  2. SpringBoot整合spring-security-oauth2完整实现例子

    SpringBoot整合spring-security-oauth2完整实现例子 技术栈 : springboot + spring-security + spring-oauth2 + mybati ...

  3. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-完整应用例子-在线聊天室系统-下载配置

    一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...

  4. SpringBoot整合Quartz作为调度中心完整实用例子

    因为想要做一个类似于调度中心的东西,定时执行一些Job(通常是一些自定义程序或者可执行的jar包),搭了一个例子,总结了前辈们的相关经验和自己的一些理解,如有雷同或不当之处,望各位大佬见谅和帮忙指正. ...

  5. spring+shiro共享session完整小例子

    之前写过一个,只不过那个不单纯,有人跑不通,所以今天整个纯粹的小例子. 要求你有Redis. 源码 GitHub 目录结构 因为这是个例子,仅仅为了体现共享session,所以权限认证部分没有加入处理 ...

  6. windows下apache httpd2.4.26集群完整搭建例子:下载、启动、tomcat集群例子

    第一部分——下载 1.1: 百度搜索apache httpd关键字,第一个链接既是官方下载地址.如果这一步不会,此篇文章不适合你阅读,请自行停止. 1.2:进入官网http://httpd.apach ...

  7. C#通过完整的例子,Get常用的2个套路,理解抽象方法,虚方法,接口,事件

    一.理解:抽象方法,虚方法,接口,事件 描述: 1.定义一个抽象父类"People": 要求: 1>3个属性:名字,性别,年龄: 2>一个普通方法"说话&qu ...

  8. Struts2 + uploadify 多文件上传完整的例子!

    首先,我这里使用的是  Jquery  Uploadify3.2版本号  导入相关的CSS  JS    <link rel="stylesheet" type=" ...

  9. ibaits的一个简单的完整的例子

    ibaits的简单介绍: iBatis 是apache 的一个开源项目,一个O/R Mapping(对象/关系映射) 解决方案,iBatis 最大的特点就是小巧,上手很快.如果不需要太多复杂的功能,i ...

随机推荐

  1. js 对象合并

    //条件 var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' } //需求如下 obj1.merge(obj2); ...

  2. nginx负载SignalR

    前几天写了篇聊天室服务器扩展随想,今天有空开始实施第一步, 聊天服务器用SignalR self-host,负载用nginx,当然这只是测试,实际使用可能还需要修改. 第一步,搭好SignalR服务, ...

  3. code vs 1098 均分纸牌(贪心)

    1098 均分纸牌 2002年NOIP全国联赛提高组  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解   题目描述 Description 有 N 堆纸牌 ...

  4. php内置的数据结构函数使用小事例

    1.栈数据结构 $stack = new splstack(); $stack->push("data1"); $stack->push("data2&quo ...

  5. windows下ThinkPHP3.2.3使用memcache缓存

    准备 要使用memcache,首先要安装配置好memcache服务memcached: 下载http://downloads.northscale.com/memcached-win64-1.4.4- ...

  6. 3.1 AngularJS必备知识

    AngularJS是一个WEB应用框架. 本节我们会学习控制器(控制数据),会学习作用域(连接控制器和用户界面),用户界面又叫做视图,通过模板和作用域来创建交互视觉效果.另外,我们还会学习其他的特性比 ...

  7. 小白请教几个关于Java虚拟机内存分配策略的问题

    最近在看周志明所著的<深入理解Java虚拟机>,有几个问题不太明白,希望对虚拟机有研究的哥们儿帮我解答一下.先说一下我进行试验的环境: 操作系统:Mac OS X 10.11.6 EI C ...

  8. 数据库邮件服务器中sp_send_dbmail的参数使用

    sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]     [ , [ @recipients = ] 'recipients [ ; n ]' ...

  9. C#中的隐式类型var——详细示例解析

    从 Visual C# 3.0 开始,在方法范围中声明的变量可以具有隐式类型var.隐式类型可以替代任何类型,它的具体类型由编译器根据上下文推断而出. 下面就让我来总结下隐式类型的一些特点: 1.va ...

  10. Delphi容器类之---TOrderedList、TStack、TQueue、TObjectStack、TObjectQueue

    TOrderedList.TStack.TQueue Contnrs单元还定义了其他三个类:TOrderedList.TStack.TQueue TOrderedList TOrderedList = ...