亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 List<CustomType> 轉換為 Dictionary

如何將 List<CustomType> 轉換為 Dictionary

C#
偶然的你 2023-08-20 15:25:01
假設我們有這個自定義類型:public class Holiday{    public Guid Id { get; } = Guid.NewGuid();    public string holidayName { get; set; };    public DateTime fromDate { get; set; };    public DateTime toDate { get; set; };    public int year { get; set; };}我需要將假期列表 ( List<Holiday>) 轉換為字典 ( Dictionary<int, List<Holiday>>)。鍵是不同的年份,值是屬于該年份的假期列表。我試圖通過查看這個答案/問題來做到這一點 ,但沒有成功。
查看完整描述

1 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

您可以使用GroupByLINQ 中的方法來完成此操作,該方法

根據指定的鍵選擇器函數對序列的元素進行分組

在您的情況下,關鍵是year語法GroupBy如下所示:

List<Holiday> holidays = new List<Holiday>

{

? ? new Holiday

? ? {

? ? ? ? year = 1999,

? ? ? ? holidayName = "Easter"

? ? },

? ? new Holiday

? ? {

? ? ? ? year = 1999,

? ? ? ? holidayName = "Christmas"

? ? },

? ? new Holiday

? ? {

? ? ? ? year = 2000,

? ? ? ? holidayName = "Christmas"

? ? }

};


Dictionary<int, List<Holiday>> holidaysByYear = holidays

? ? .GroupBy(h => h.year)

? ? .ToDictionary(h => h.Key, h => h.ToList());


foreach (KeyValuePair<int, List<Holiday>> holidaysInYear in holidaysByYear)

{

? ? Console.WriteLine($"Holidays in {holidaysInYear.Key}");

? ? foreach (Holiday holiday in holidaysInYear.Value)

? ? {

? ? ? ? Console.WriteLine(holiday.holidayName);

? ? }

}

其產生的輸出為:

https://img2.sycdn.imooc.com/64e1c00600019a1202620211.jpg


查看完整回答
反對 回復 2023-08-20
  • 1 回答
  • 0 關注
  • 125 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號