C#集合类用法实例代码详解
下面介绍C#的集合类
1ArrayList
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Collections;
namespace动态数组ArrayList
{
classProgram
{
staticvoidMain(string[]args)
{
ArrayLista1=newArrayList();
a1.Add(100);
foreach(intnumberinnewint[6]{9,3,7,2,4,8})
{
a1.Add(number);
}
int[]number2=newint[2]{11,12};
a1.AddRange(number2);
a1.Remove(3);
a1.RemoveAt(3);
ArrayListal2=newArrayList(a1.GetRange(1,3));
Console.WriteLine("遍历方法1:");
foreach(intiina1)
{
Console.WriteLine(i);
}
Console.WriteLine("遍历方法2:");
for(inti=0;i
2 Stack
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Collections;
namespaceStack集合类
{
classProgram
{
staticvoidMain(string[]args)
{
Stacks1=newStack();
Stacks2=newStack();
foreach(intiinnewint[4]{1,2,3,4})
{
s1.Push(i);
s2.Push(i);
}
foreach(intiins1)
{
Console.WriteLine(i);
}
s1.Pop();
Console.WriteLine("出栈");
foreach(intiins1)
{
Console.WriteLine(i);
}
intnum=(int)s2.Peek();
Console.WriteLine("弹出最后一项{0}",num);
foreach(intiins2)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
3Queue
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Collections;
namespaceQueue集合类
{
classProgram
{
staticvoidMain(string[]args)
{
Queueq1=newQueue();
Queueq2=newQueue();
foreach(intiinnewint[4]{1,2,3,4})
{
q1.Enqueue(i);
q2.Enqueue(i);
}
foreach(intiinq1)
{
Console.WriteLine(i);
}
q1.Dequeue();
Console.WriteLine("q1出队");
foreach(intiinq1)
{
Console.WriteLine(i);
}
intnum=(int)q2.Peek();
Console.WriteLine("取q2开始处{0}",num);
foreach(intiinq2)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
4Hashtable
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Collections;
namespaceHashtable集合类
{
classProgram
{
staticvoidMain(string[]args)
{
Hashtableh=newHashtable();
h.Add("E","e");
h.Add("B","b");
h.Add("C","c");
h.Add("A","a");
foreach(DictionaryEntryeinh)
{
Console.Write("{0},{1}",e.Key,e.Value);
}
Console.WriteLine();
strings=(string)h["C"];
Console.WriteLine(s);
if(h.Contains("E"))
{
Console.WriteLine("含有E");
}
Console.WriteLine(h["A"]);
h.Remove(h["A"]);
h.Clear();
foreach(DictionaryEntryeinh)
{
Console.Write("{0},{1}",e.Key,e.Value);
}
Console.ReadLine();
}
}
}
5SortedList
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Collections;
namespaceSortedList集合类
{
classProgram
{
staticvoidMain(string[]args)
{
SortedLists1=newSortedList();
s1["c"]=41;
s1["a"]=42;
s1["d"]=11;
s1["b"]=13;
foreach(DictionaryEntryeins1)
{
strings=(string)e.Key;
inti=(int)e.Value;
Console.Write("{0},{1}",s,i);
}
Console.ReadLine();
}
}
}
总结
以上所述是小编给大家介绍的C#集合类用法实例代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!