本文参考:http://wenku.baidu.com/view/9ceffbd95022aaea998f0f61.html
以下为示例源码,VS2008编译通过:
int count = 0;
private void Form1_Load(object sender, EventArgs e)
{
TestList();
}
private void TestList()
{
string[] temArr = { "cc", "aaaa", "bbb" };
List<string> mList = new List<string>();
mList.AddRange(temArr);
//List添加操作
mList.Add("dd");
mList.Insert(0, "ee");
ShowList(mList);
//List排序操作
mList.Sort();
ShowList(mList);
mList.Reverse();
ShowList(mList);
//List删除操作
if (mList.Remove("cc"))
{
Console.WriteLine("cc has been deleted");
}
mList.RemoveAt(0);
ShowList(mList);
mList.RemoveRange(1, 2);
//List查找操作
if (mList.Contains("cc"))
{
Console.WriteLine("there is cc in the list");
}
mList.AddRange(temArr);
ShowList(mList);
//List的Find方法,FindLast用法与其相同,委托给一个函数或拉姆达表达式
string listFind = mList.Find(name =>
{
if (name.Length > 1)
{
return true;
}
return false;
});
//委托给ListFind2函数,与上种方法效果相同
//string listFind = mList.Find(ListFind2);
Console.WriteLine("------长度大于1的第一个元素:"+listFind);
//RemoveAll方法与FindAll用法相似
bool flag = mList.TrueForAll(ListFind2);
Console.WriteLine("------True for all :" + flag);
//FindAll返回所有满足条件的元素
List<string> subList = mList.FindAll(ListFind2);
ShowList(subList);
//List的Where方法与Take相似
IEnumerable<string> takeList = mList.Take(2);
foreach(string s in takeList)
{
Console.WriteLine("前两个元素:"+s);
}
string []strArr = mList.ToArray();
foreach (string s in strArr)
{
Console.WriteLine("数组:"+s);
}
}
/// <summary>
/// 委托给一个函数
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private bool ListFind2(string name)
{
if (name.Length > 2)
{
return true;
}
return false;
}
/// <summary>
/// 输出List所以数据
/// </summary>
/// <param name="list"></param>
private void ShowList(List<string> list)
{
count++;
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(count+":"+list[i]);
}
//foreach (string s in mList)
//{
// Console.WriteLine("------" + s);
//}
}
输出为:
1:ee
1:cc
1:aaaa
1:bbb
1:dd
2:aaaa
2:bbb
2:cc
2:dd
2:ee
3:ee
3:dd
3:cc
3:bbb
3:aaaa
cc has been deleted
4:dd
4:bbb
4:aaaa
5:dd
5:cc
5:aaaa
5:bbb
------长度大于1的第一个元素:dd
------True for all :False
6:aaaa
6:bbb
前两个元素:dd
前两个元素:cc
数组:dd
数组:cc
数组:aaaa
数组:bbb