Reputation: 6202
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
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
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
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