集合-字典(Lookup/SortedDictionary)

时间:2021-11-22 07:01:10

Lookup<TKey, TElement>非常类似于Dictionary<TKey, TValue>,但是把键映射在一个值集上。

必须调用ToLookup方法创建Lookup<TKey, TElement>对象。Lookup<TKey, TElement>对象是不可变的,无法向对象添加,移除元素。

public class User
{
public string Address;
public string Name;
public int Age;
}
class Program
{
static void Main(string[] args)
{
List<User> users = new List<User> { new User{Address="bj",Name="rxm",Age=},
new User{Address="bj",Name="cwr",Age=},
new User{Address="sh",Name="zcl",Age=},
new User{Address="zz",Name="hst",Age=}}; Lookup<char, string> needUsers = (Lookup<char, string>)users.ToLookup(p => Convert.ToChar(p.Address.Substring(, )),
p => p.Name + "-" + p.Age.ToString()); foreach (IGrouping<char, string> item in needUsers)
{
Console.WriteLine(item.Key); //b s z
foreach (string str in item)
{
Console.WriteLine(" {0}", str);
}
}
//-----
Console.WriteLine("--------------");
IEnumerable<string> results = needUsers['b'];
foreach (var item in results)
{
Console.WriteLine(item);
}
Console.Read();
}
}

SortedDictionary<Tkey,Tvalue>中的键都必须唯一。与这个Dictionary<Tkey,Tvalue>类不同的是,它排了序。

 SortedDictionary<string, string> items = new SortedDictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);//忽略大小写
items.Add("masanli", "逗你玩");
items.Add("maji", "宇宙牌香烟");
items.Add("liubaorui", "连升三级");
items.Add("houbaolin", "北京话");
foreach (KeyValuePair<string, string> item in items)
{
Console.WriteLine(string.Format("key:{0},value:{1}", item.Key, item.Value));
}