I have a class that is defined like this:
Multiple ClassA are stored stored in List(). I and to create a List based off all the ContractID's in List. Is there a way in LINQ to be able to do this instead of iterating through List()?
You can use the
Select extension method to create a projection of the contractID. Like:
var listOfClass = new List<ClassA>(); //Or however you get your list. var contractIDs = listOfClass.Select(x => x.contractID).ToList();
var onlyContractIDs = myList.Select(x => x.contractID).ToList()
List<ClassA> input = ...; List<int> output = input.Select(a => a.contractID).ToList();
Select is a generic method. Explicitly specified, it would be
Select<ClassA, int>, specifying the input and output types.
ToList() at the end converts from an
IEnumerable<int> to a
List<int>, and it does the iteration over the input list now, rather than when the
IEnumerable<int> is enumerated.
If you have a List you can make a List with LINQ like this
List<int> contractIDs = mycollection.Select(a => a.ContractID).ToList();
var list = new List<ClassA>(); ... list.Select(a => a.ContractID);