對 Dictionary 的認知就是 key、value 組合,所以使用 ToDictionary() 時,很直覺會是需要輸入 key、value,看 MSDN 時發現原來有只輸入 key 的 overload 可以使用,value 會直接是該物件型別
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--------- 個人原寫法 ---------");
Dictionary<long, Package> jt = DemoHelper.GetData()
.ToDictionary(k => k.TrackingNumber, v => v);
DemoHelper.ShowData(jt);
Console.WriteLine("--------- ToDictionary() 多載 ---------");
Dictionary<long, Package> msdn = DemoHelper.GetData()
.ToDictionary(k => k.TrackingNumber);
DemoHelper.ShowData(msdn);
}
}
class Package
{
public string Company { get; set; }
public double Weight { get; set; }
public long TrackingNumber { get; set; }
public override string ToString()
{
return $"{TrackingNumber} ,{Company}, {Weight}";
}
}
static class DemoHelper
{
public static List<Package> GetData()
{
return
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 } };
}
public static void ShowData(Dictionary<long, Package> Data)
{
foreach (var item in Data)
{
Console.WriteLine(item.ToString());
}
}
}
}
沒有留言:
張貼留言