views:

75

answers:

2

Hello, I have an IList which contains a custom type. One of the properties of that custom type is called ID. How could I convert that without using a for loop? The array should not be of the CustomType, but if the type of ID, which is int.

Thanks!

+12  A: 

Hi there.

Try:

sourceList.Select(i => i.ID).ToArray();

Where sourceList is your list of type IList<CustomType>.

Cheers. Jas.

Jason Evans
This returns a nullable, doesnt it? The method I am calling with this array doesnt take nullable types...what do I have to change?
grady
@grady - The returned array is not a collection of nullable ints, it will be a `int[]` type, not `int?[]`. In fact, if you this code 'int?[] newArray = ......' then it will fail.
Jason Evans
Are you sure about that? The compiler complains about it...I have a method which gets an array of ints and there the error is thrown.
grady
@grady, this would only return nullable ints if the type of ID was a nullable int. If ID is int? and you want int, you would want to create a chain like `sourceList.Where(i => i.ID.HasValue).Select(i => i.ID.Value).ToArray();` The `Where` eliminates any IDs that may not have values, and `Select` will extract the int values.
Anthony Pegram
Ah yes, you are right, it works now!
grady
A: 

Hi - Something like this

    IList<x> xList = new List<x>{ new x() { ID = 1, Name = "Alice"}, new x() { ID = 2, Name = "Bob"}};
    int[] myInts = xList.Select(myItem => myItem.ID).ToArray();
nonnb