字典列表(C#) [英] Dictionary to List (C#)

查看:279
本文介绍了字典列表(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是一个问题,但如果有更好的方法,我很好奇。基本上,我有一个字典,其中的关键是我创建的一个结构体。我需要做的是获取密钥中某个属性的列表。即在结构体中我有一个名为'ID'的字段,我想得到一个列表。我现在在做的是这样的:

 列表< long> keys = new List< long>(); 
foreach(var key in dict.Keys)
{
keys.Add(key.ID);
}

这个工作,但我只是想知道如果我错过了更容易方法 - 起初我认为可能会给出ToList方法一个参数,所以我可以在列表中指定我想要的struct的哪一部分,但似乎不可以。



你如何改善这一点?

解决方案

你可以使用LINQ:

 列表< long> keys = dict.Keys.Select(k => k.ID).ToList(); 

您可以将ID传递给 Select()而不是 ToList(),并且只调用 ToList()将生成的集合转换为列表。 p>

Not really a problem, but I'm curious if there's a nicer way of doing this. Basically, I have a dictionary, where the key is a struct that I have created. What I need to do is get a list of a certain property in the keys. I.e. in the struct I have a field called 'ID', which I want to get a list of. What I'm doing now is this:

List<long> keys = new List<long>();
foreach(var key in dict.Keys)
{
     keys.Add(key.ID);
}

This works but I'm just wondering if I'm missing an even easier way - at first I thought perhaps the ToList method could be given a parameter so I can specify which part of the struct I want in the list, but it doesn't seem I can.

How would you guys improve this?

解决方案

You can use LINQ:

List<long> keys = dict.Keys.Select(k => k.ID).ToList();

Here you pass the ID to Select() rather than ToList(), and only call ToList() to convert the resulting collection to a list.

这篇关于字典列表(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆