简体   繁体   English

如何在C#中将列表列表转换为字典?

[英]How do I convert a list of lists to dictionary in C#?

I have a list of boxes(unique, with id) and in each box there are certain items(unique, with id). 我有一个盒子列表(唯一,带有ID),每个盒子里都有某些物品(唯一,带有ID)。 Example: 例:

list<box> boxes = new list<boxes>;

where, 哪里,

class box
{   ...
    list<item> items = new list<item>;
    ...
}
  • Box1: item1, item2, ... Box1:item1,item2,...
  • Box2: item4, item5, ... Box2:项目4,项目5,...
  • Box3: ... Box3:...

I need to find the item details, given the item id. 给定商品ID,我需要找到商品详细信息。 For this I current do something like this: 为此,我目前正在做这样的事情:

foreach (box b in boxes)
{
    foreach (item i in b.items)
    {
        if (i.id == searchId)
            return i;
    }
}

Question is: How can I convert this list data structure to a dictionary data structure? 问题是:如何将该列表数据结构转换为字典数据结构?

As I have keys (Id), so I think using a dictionary would be a better choice? 因为我有键(Id),所以我认为使用字典会是更好的选择?

If it's possible that same items can exist in several boxes, you can select all items, and group them by id, then select first item from each group as a value for dictionary: 如果相同的项目可能存在于多个框中,则可以选择所有项目,然后按ID进行分组,然后从每个组中选择第一个项目作为字典的值:

Dictionary<int, item> items = boxes.SelectMany(b => b.items)
                                   .GroupBy(i => i.id)
                                   .ToDictionary(g => g.Key, g.First());

If all items have unique ids: 如果所有项目都有唯一的ID:

var items = boxes.SelectMany(b => b.items)                     .
                 .ToDictionary(i => i.id);

Getting item will look like: 获取项目如下所示:

if (items.ContainsKey(searchId))
    return items[searchId];

As @Douglas stated, to avoid double lookup it's better to use TryGetValue method: 如@Douglas所述,为避免重复查找,最好使用TryGetValue方法:

item i;
if (items.TryGetValue(searchId, out i))
    return i;

NOTE: Linq alternative without dictionary will be (it does exactly same as your code - enumerates boxes and their items for each search): 注意:不带字典的Linq替代品将是(它与您的代码完全相同-每次搜索都列举方框及其项目):

var item = boxes.SelectMany(b => b.items).FirstOrDefault(i => i.id == searchId);

So, if you don't want to hold dictionary with items between searches, or if you need to execute single search, then you can use this solution. 因此,如果您不想在每次搜索之间都包含字典,或者如果您需要执行单个搜索,那么可以使用此解决方案。

Assuming all your items are unique: 假设您的所有商品都是唯一的:

var dictionary = boxes.SelectMany(box => box.items).ToDictionary(item => item.id);

You can then look up values using: 然后,您可以使用以下方法查找值:

item i;
if (dictionary.TryGetValue(searchID, out i))
    return i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM