简体   繁体   中英

Convert IEnumerable to List of properties

Say I have a class called Event:

public class Event
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Description { get; set; }
}

And have the following query:

var events = _eventInformationRepository.Fetch(e => e.Id != -1);

Which returns an IEnumerable<Event> . But I'd like to create a list of IDs of events. Can this be done directly via ienum? Or do I have to generate the list, iterate, assign and add each value?

Just use the Linq Select method:

var events = ...
var eventIDs = events.Select(e => e.Id);

This will return an IEnumerable<int> , which should be enough for most purposes. However, if you really want a List<int> you can just call the ToList method:

var eventIDs = events.Select(e => e.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