《C#本质论》读书笔记(16)构建自定义集合
Posted 【唐】三三
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《C#本质论》读书笔记(16)构建自定义集合相关的知识,希望对你有一定的参考价值。
16.1 更多集合接口
集合类(这里指IEnumerable层次结构)实现的接口层次结构
16.1.1 IList<T>与IDictionary<TKey,TValue>
IList<T>
(侧重位置索引获取值)与 IDictionary<TKey,TValue>
(侧重通过键来获取值)。16.1.2 ICompatable<T>
高级主题:用IComparer<T>排序
public static void Main()
{
Contact aaa = new Contact() { LastName = "bbb", FirstName = "ddd" };
Contact bbb = new Contact() { LastName = "aaa", FirstName = "ccc" };
//Console.WriteLine(new NameComparison().Compare(aaa, bbb));
List<Contact> contactlist = new List<Contact>();
contactlist.Add(aaa);
contactlist.Add(bbb);
foreach (var contact in contactlist)
{
Console.WriteLine(contact.LastName + " ");
}
//排序
contactlist.Sort(new NameComparison());
foreach (var contact in contactlist)
{
Console.WriteLine(contact.LastName + " ");
}
Console.Read();
}
class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class NameComparison : IComparer<Contact>
{
public int Compare(Contact x, Contact y)
{
int result;
if (Contact.ReferenceEquals(x, y))
{
result = 0;
}
else
{
if (x == null)
{
result = 1;
}
else if (y == null)
{
result = -1;
}
else
{
result = StringCompare(x.LastName, y.LastName);
if (result == 0)
{
result =
StringCompare(x.FirstName, y.FirstName);
}
}
}
return result;
}
private static int StringCompare(string x, string y)
{
int result;
if (x == null)
{
if (y == null)
{
result = 0;
}
else
{
result = 1;
}
}
else
{
result = x.CompareTo(y);
}
return result;
}
}
16.2.1 列表集合:List<T>
List<string> list = new List<string>();
// Lists automatically expand as elements
// are added.
list.Add("Sneezy");
list.Add("Happy");
list.Add("Dopey");
list.Add("Doc");
list.Add("Sleepy");
list.Add("Bashful");
list.Add("Grumpy");
list.Sort();
Console.WriteLine(
"In alphabetical order {0} is the "
+ "first dwarf while {1} is the last.",
list[0], list[6]);
list.Remove("Grumpy");
16.2.3 搜索List<T>
List<string> list = new List<string>();
int search;
list.Add("public");
list.Add("protected");
list.Add("private");
list.Sort();
search = list.BinarySearch("protected internal");
if (search < 0)
{
list.Insert(~search, "protected internal");
}
foreach (string accessModifier in list)
{
Console.WriteLine(accessModifier);
}
高级主题:使用 FindAll() 查找多个数据项
public static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(2);
- C#本质论读书笔记
JAVA笔记(16)---集合- 详解 Set集合( Map 体系集合常用方法;哈希表;二叉树数据结构;Map集合,如何自定义集合排序规则 )