For example:
public List<Data> dataList;
public List<int> idList;
public class Data
{
public int id;
public string name;
}
I need to get all 'id' variables from 'dataList' into 'idList'. Something like that
public List<Data> dataList;
public List<int> idList
{
get
{
for (int i = 0; i < dataList.Count; i )
{
idList.Add(dataList[i].id);
}
return idList
}
};
But how to optimize this in a better way?
I tried to create local list, populate it with ids and then give it to the 'idList'. But I think this method is not optimized
CodePudding user response:
You can use Linq Select
for that. select
can be use to "project" from your object collection to another collection (in your case, List of int
)
public List<Data> dataList;
public List<int> idList
{
get
{
return dataList.Select(x => x.id).ToList();
};
}
More about Linq
here - https://docs.microsoft.com/en-us/previous-versions/bb397926(v=vs.140)?redirectedfrom=MSDN