Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to populate List<int> from List<class> that contains int variable in getter

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading