如何將對象列表轉換為兩級字典? (How to convert a list of objects to two level dictionary?)


問題描述

如何將對象列表轉換為兩級字典? (How to convert a list of objects to two level dictionary?)

I have a list of customer objects (e.x:  List customers)

 public class Customer
    {
        public int ID { get; set; }
        public string City { get; set; }
        public bool DidLive { get; set; }
    }

What I need to do is to convert this "customers" collection into a dictionary like follows,

"Dictionary<int, Dictionary<string, bool>>"  Where the outer key is the "ID" and the inner key is the "City".

Can this be done using "GroupBy" or "ToDictionary" extension methods of "IEnumerable<T>"?

‑‑‑‑‑

參考解法

方法 1:

I'm assuming here that you have multiple Customer objects with the same Id but with different Cities (if this isn't the case and  the inner dictionary will always contain one item, go with @oleksii's answer). 

var result = customers.GroupBy(c => c.Id)
                      .ToDictionary(group => group.Key,
                                    group => group.ToDictionary(c => c.City, 
                                                                c => c.DidLive));

Of course, this will throw an exception if there multiple customers with identical Ids and Cities.

方法 2:

That's a place to start

var data = new List<Customer>();

data.ToDictionary(item => item.ID, 
                    item => new Dictionary<string, bool>
                    {
                        {item.City,item.DidLive}
                    });

(by CherangaAnioleksii)

參考文件

  1. How to convert a list of objects to two level dictionary? (CC BY‑SA 3.0/4.0)

#collections #Dictionary #C# #extension-methods






相關問題

C ++中集合/容器的接口/超類 (Interface/Superclass for Collections/Containers in c++)

如何將對象列表轉換為兩級字典? (How to convert a list of objects to two level dictionary?)

如何在java中限制哈希集的默認排序 (how to restrict default ordering of Hash Set in java)

將兩個單獨的 Set 轉換為二維數組 (Convert two separate Sets to a 2D array)

事件調度線程從列表異常 SWING 中移除 (Event dispatching thread remove from List exception SWING)

將集合項複製到 .NET 中的另一個集合 (Copy collection items to another collection in .NET)

java - 如何在java中使用某些特定索引將值存儲到arraylist中 (how to store value into arraylist with some specific index in java)

將對象添加到具有主幹的第一個位置的集合中? (Adding object to a Collection in the first position with backbone?)

在VB中過濾一個wpf collectionviewsource? (Filter a wpf collectionviewsource in VB?)

將流式數據讀入排序列表 (Reading streamed data into a sorted list)

有沒有一種自動處理數組和強類型集合之間轉換的好方法? (Is there a good way to handle conversions between arrays and strongly typed collections automatically?)

將數據行轉換為 1 個對象 (Convert data rows to 1 object)







留言討論