简体   繁体   中英

Dictionary to List (C#)

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. Ie 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.

Using Select (From Linq) for the projection and ToArray to create a concrete list. (Or ToList if you need to modify the resulting collection later)

var keys = dict.Keys.Select(k => k.ID).ToArray();

Using Linq:

var keys = dict.Keys.Select(p => p.ID).ToList();

Using one of the constructors of List

var keys = new List<long>(dict.Keys.Select(p => p.ID));

(the constructor accepts an IEnumerable<T> , and the Select on dict.Keys clearly is it)

and using AddRange

var keys = new List<long>();
keys.AddRange(dict.Keys.Select(p => p.ID));

In general we are using the .Select "of" Linq to solve the problem. Clearly we could have written:

from p in dict.Keys select p.ID 

instead of

dict.Keys.Select(p => p.ID)

I'll note the only interesting difference is for the AddRange : the other "ways" create a new List and fill it. AddRange adds to a preexisting List that could already have elements.

使用linq将id作为列表返回:

List<long> result = dic.Select(x => x.Key.ID).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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