samus
samus

Reputation: 6202

Initialize a List<int> from a List<object> enumeration

Is it possible to initialize a List of int (primitives/value-types) with an enumeration of a List of objects that contain the desired integer property?

I have a list of records, List<Record>, that have RecordId's.

Is it possible to initialize a List<int> of these RecordId's in the following vein:

List<Record> records;

List<int> recordIds = new List<int> { records.GetEnumerator().Current.RecordId };

Upvotes: 2

Views: 178

Answers (3)

John Wu
John Wu

Reputation: 52270

First, write a function that will accept a record and produce the desired integer.

public int GetID(Record r)
{
    return r.RecordId; 
}

You can also write is as a lambda.

r => r.RecordId;

Then pass the function to LINQ's Select method:

//using System.Linq;
var result = records.Select(GetID);

Note that GetID is passed, not GetID(). You want to pass a reference to the function, not the result of the function.

You can also pass the lambda, which is a much more common way to do it:

var result = records.Select( r => r.RecordId );

If you want to end up with a list, just add ToList() to the end.

var result = record.Select( r => r.RecordId ).ToList();

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56443

Another solution would be:

List<int> recordIds = new List<int>(records.Count);
foreach(var record in records)
      recordIds.Add(record.RecordId);

or using query syntax:

IEnumerable<int> recordIds = 
         from record in records
         select record.RecordId;

Upvotes: 2

McAden
McAden

Reputation: 13970

Either of these should work.

List<int> recordIds = new List<int>(records.Select(e => e.RecordId));

or

List<int> recordIds = records.Select(e => e.RecordId).ToList();

Under the covers these are practically identical so I'd use whichever you find is most readable.

Upvotes: 3

Related Questions