1. Array
//创建方式
//方式一
Array arr = Array.CreateInstance(typeof(string), 3);
arr.SetValue("lisi", 0);
arr.SetValue("zhangsan", 1);
arr.SetValue("lili", 2);
foreach (var item in arr)
{
Console.WriteLine(item);
}
//还可以转换
string[] strArr = (string[])arr;
foreach (var item in strArr)
{
Console.WriteLine(item);
}
//还可以这样遍历
Array.ForEach(strArr, Console.WriteLine);
//输出
lisi
zhangsan
lili
1.1 搜索
- IndexOf / LastIndexOf 从头往后找 / 从后往前找
- Find / FindLast / FindIndex / FindAll / Exists / TrueForAll
- BinarySearch 二叉查找
string[] names = {
"lisi", "xiaoli", "andy", "lucy" };
//IndexOf
int los = Array.IndexOf(names, "andy");
int Llos = Array.LastIndexOf(names, "andy");
Console.WriteLine(los);
Console.WriteLine(Llos);
//Find
string? temps = Array.Find(names, n => n.Contains('a'));
Console.WriteLine(temps);
//xiaoli
string? templ = Array.FindLast(names, n => n.Contains('a'));
Console.WriteLine(templ);
//andy
//FindAll
string[] tempstr = Array.FindAll(names, n => n.Contains('a'));
Array.ForEach(tempstr, Console.WriteLine);
//xiaoli
//andy
//Exists
bool isExists = Array.Exists(names, n => n.Contains('a'));
Console.WriteLine(isExists);
//True
//TrueForAll 是不是所有的都满足条件
bool isTrueAll = Array.TrueForAll(names, n => n.Contains('a'));
Console.WriteLine(isTrueAll);
//False
string[] nas = {
"andy", "sandy" };
bool isNasAll = Array.TrueForAll(nas, n => n.Contains('a'));
Console.WriteLine(isNasAll);
//True
//BinarySearch
int biLos = Array.BinarySearch(names, "xiaoli");
Console.WriteLine(biLos);
//1
1.2 排序
int[] numbers = {
1, 3, 2};
string[] words = {
"yi", "san", "er" };
Array.Sort(numbers);
Array.ForEach(numbers, Console.Write);
//123
//第一个数组的排序,同时应用到第二个数组
Array.Sort(numbers, words);
Array.ForEach(numbers, Console.Write);
Array.ForEach(words, Console.Write);
//123yiersan
1.3 翻转
int[] numbers = {
1, 3, 2};
string[] words = {
"yi", "san", "er" };
Array.Reverse(numbers);
Array.ForEach(numbers, Console.Write);
//231
1.4 转换
float[] fls = {
1.5f, 2.3f, 2.5f };
int[] ints = Array.ConvertAll(fls, r => Convert.ToInt32(r));
Array.ForEach(ints, Console.Write);
//222
2. List
List有ArrayList和LinkedList
- ArrayList 类似数组,查找快,插入删除慢(相对)
- LinkedList 类似双向链表,查找慢(相对),插入删除快
//ArrayList
//ArrayList
ArrayList arrList = new ArrayList();
arrList.Add("andy");
arrList.Add("sandy");
arrList.Add("sunny");
arrList.RemoveAt(1);
arrList.Reverse();
arrList.Insert(1, "tom");
arrList.InsertRange(0, new[] {
"times","jerry"});
foreach (var item in arrList)
{
Console.WriteLine(item);
}
/*
times
jerry
sunny
tom
andy
*/
//LinkList
//LinkList
LinkedList<string> linkArr = new LinkedList<string>();
//从头部加入
linkArr.AddFirst("andy");
linkArr.AddFirst("sandy");
linkArr.AddFirst("sunny");
//sunny
//sandy
//andy
//从尾部加入
linkArr.AddLast("tom");
linkArr.AddLast("jerry");
/*
sunny
sandy
andy
tom
jerry
*/
//在顺数第三个位置添加元素
linkArr.AddAfter(linkArr.First.Next, "get");
//在倒数第三个位置添加元素
linkArr.AddBefore(linkArr.Last.Previous, "give");
foreach (var item in linkArr)
{
Console.WriteLine(item);
}
/*
sunny
sandy
get
andy
give
tom
jerry
*/
3. Queue
队列,先进先出
Queue<string> queue = new Queue<string>();
queue.Enqueue("tom");
queue.Enqueue("jerry");
queue.Enqueue("times");
string deTemp = queue.Dequeue();
Console.WriteLine("dequeue ele is "+deTemp);
Console.WriteLine(queue.Count);
Console.WriteLine(queue.Contains("tom"));
//给容器瘦身
queue.TrimExcess();
string[] strArr = queue.ToArray();
foreach (var item in strArr)
{
Console.WriteLine(item);
}
/*
dequeue ele is tom
2
False
jerry
times
*/
4. Stack
栈,先进后出
Stack<string> strArr = new Stack<string>();
strArr.Push("tom");
strArr.Push("jerry");
strArr.Push("lily");
Console.WriteLine(strArr.Count);
strArr.TrimExcess();
strArr.Pop();
string topEle = strArr.Peek();
Console.WriteLine(topEle);
string[] strSta = strArr.ToArray();
foreach (var item in strSta)
{
Console.WriteLine(item);
}
//3
//jerry
//jerry
//tom
5. BitArray
位数组,用来保存bit的集合,它只保存一个位,也就是只能保存true或false
这个数组只有四个操作,And,Or,Xor,Not
BitArray bitArray = new BitArray(3);
bitArray[0] = true;
bitArray[1] = true;
bitArray[2] = false;
BitArray bit1 = bitArray.And(bitArray);
foreach (var item in bit1)
{
Console.WriteLine(item);
}
//True
//True
//False
Console.WriteLine("----------------");
BitArray bit2 = bitArray.Or(bitArray);
foreach (var item in bit2)
{
Console.WriteLine(item);
}
//True
//True
//False
Console.WriteLine("----------------");
BitArray bit3 = bitArray.Xor(bitArray);
foreach (var item in bit3)
{
Console.WriteLine(item);
}
//False
//False
//False
Console.WriteLine("----------------");
BitArray bit4 = bitArray.Not();
foreach (var item in bit4)
{
Console.WriteLine(item);
}
//True
//True
//True
6. Set
有 HashSet 和 SortedSet,
- 它们都不包含重复元素
- 忽略添加重复值的请求
- 无法根据位置访问元素
- 使用Contains方法均使用散列查找,所以速度快
SortedSet 按照一定顺序保存元素,使用红黑树实现,而HashSet是根据Hash值保存元素和查找元素。
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
foreach (var item in evenNumbers)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------");
foreach (var item in oddNumbers)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------");
HashSet<int> numbers = new HashSet<int>(evenNumbers);
foreach (var item in numbers)
{
Console.WriteLine(item);
}
Console.WriteLine("--------------------------");
numbers.UnionWith(oddNumbers);
foreach (var item in numbers)
{
Console.WriteLine(item);
}
/*
2
4
6
8
--------------------------
1
3
5
7
9
--------------------------
0
2
4
6
8
--------------------------
0
2
4
6
8
1
3
5
7
9
*/
7. Dictionary
字典是键值对集合,通过键值对来查找
Dictionary和Hashtable的区别是Dictionary可以用泛型,而HashTable不能用泛型
OrderedDictionary 是按照添加元素时的顺序的字典,是一个非泛型字典,可以用索引访问文员,也可以用键来访问元素,类似HashTable和ArrayList的结合
其他类型:
ListDictionary是使用一个独立链表来存储实际的数据,数据多时效率不好
HybridDictionary是为了解决ListDictionary数据多时效率不好的情况,用来替代ListDictionary。
- SortedDictionary,内部由红黑树实现,内部根据键进行排序
//Hashtable
Hashtable hashtable = new Hashtable();
hashtable.Add("name", "lisi");
hashtable.Add("txt", "notepad.exe");
hashtable.Add("bmp", "paint.exe");
hashtable.Add("dib", "paint.exe");
hashtable.Add("rtf", "wordpad.exe");
try
{
hashtable.Add("txt", "winword.exe");
}
catch (Exception)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
Console.WriteLine("For key = \"txt\", value = {0}.", hashtable["txt"]);
//An element with Key = "txt" already exists.
//For key = "txt", value = notepad.exe.
foreach (DictionaryEntry de in hashtable)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
//Key = dib, Value = paint.exe
//Key = bmp, Value = paint.exe
//Key = rtf, Value = wordpad.exe
//Key = name, Value = lisi
//Key = txt, Value = notepad.exe
if (!hashtable.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
//Dictionary
Dictionary<string, int> dics = new Dictionary<string, int>();
dics.Add("name", 123);
dics.TryAdd("name", 456);//如果有了键,那么就不会再添加了
dics.TryAdd("age", 50);
dics["age"] = 45; //修改
dics.Remove("age");
dics.Remove("time");//不管有没有也不报错
Console.WriteLine(dics["name"]);
int value;
Console.WriteLine(dics.TryGetValue("name",out value));
Console.WriteLine(value);
//123
//True
//123
8. 自定义集合Collection
Collection可以对添加删除元素或者添加删除属性进行事件响应。
class Person
{
public string name;
public int age;
public Person()
{
this.name = "";
this.age = 0;
}
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public override string ToString()
{
return this.name + "," + this.age;
}
}
class PersonCollection : Collection<Person>
{
protected override void InsertItem(int index, Person item)
{
base.InsertItem(index, item);
Console.WriteLine("insert ele: index id {0},item is {1}",index,item.ToString());
}
protected override void SetItem(int index, Person item)
{
base.SetItem(index, item);
Console.WriteLine("set ele: index id {0},item is {1}", index, item.ToString());
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
Console.WriteLine("remove ele: index id {0}", index);
}
protected override void ClearItems()
{
base.ClearItems();
Console.WriteLine("collect is clear");
}
}
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
PersonCollection people = new PersonCollection();
people.Add(new Person());
people.Insert(0, new Person("lisi", 50));
people[1] = new Person("anger", 19);
people.RemoveAt(1);
foreach (var item in people)
{
Console.WriteLine(item.ToString());
}
}
}
9. 其他
方法:string.Compare
string str1 = "help";
string str2 = "Help";
string str3 = "help";
int res = string.Compare(str1, str2);
int res1 = string.Compare(str1, str3);
Console.WriteLine(res); //-1
Console.WriteLine(res1); //0