C#中ToDictionary,ToLookup
C#中ToDictionary,ToLookup一、C#中ToDictionary
ToDictionary中并没有给我们做key的重复值判断,那也就侧面说明ToDictionary在kv中只能是 “一对一”的关系,也就是v中永远只会有一条记录
定义
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
实例
class Package
{
public string Company { get; set; }
public double Weight { get; set; }
public long TrackingNumber { get; set; }
}
public static void ToDictionaryEx1()
{
List<Package> packages =
new List<Package>
{ new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L },
new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L },
new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L },
new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } };
// Create a Dictionary of Package objects,
// using TrackingNumber as the key.
Dictionary<long, Package> dictionary =
packages.ToDictionary(p => p.TrackingNumber);
foreach (KeyValuePair<long, Package> kvp in dictionary)
{
outputBlock.Text += String.Format(
"Key {0}: {1}, {2} pounds",
kvp.Key,
kvp.Value.Company,
kvp.Value.Weight) + "\\n";
}
}
二、C#中ToLookup
ToLookup() 方法创建一个类似 字典(Dictionary ) 的列表,这是一个one-to-many集合,一个Key可以对应多个Value。
Lookup,不像Dictionary, 是不可改变的。 这意味着一旦你创建一个lookup, 你不能添加或删除元素。
定义
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
实例1
var dic = ticketlist.ToLookup(i => i.OrderID);
foreach (var item in dic)
{
Console.WriteLine("订单号:" + item.Key);
foreach (var item1 in item)
{
Console.WriteLine("\\t\\t" + item1.TicketNo + " " + item1.Description);
}
}
实例2、得到某个类别的所有产品
private static void PrintCategory(ILookup<string, Product> productsByCategory,string categoryName)
{
foreach (var item in productsByCategory[categoryName])
{
Console.WriteLine(item);
}
}