问题描述:

I have a class that is defined like this:

class A

{

int contractID;

string name;

string blah;

etc...

}

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.

The 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);
相关阅读:
Top