Home > Mobile >  Getting List<List<int>> but want just List<int>
Getting List<List<int>> but want just List<int>

Time:06-08

I have the following variable,

var actionIds = formFields.Select(x => x.GridDefinition.Actions.ToList().Select(y =>y.DFActionID).ToList()).ToList();

It is giving me the result as List<List<int> but I want the result as List<int> How should I go about it?

Later I need to check IDs from the above list with a single ID like the below.

var removedFormFieldsActions = existingFormFieldsActions.Where(x => !actionIds.Contains(x.DFActionID));

Which is currently giving an error.

CodePudding user response:

There are a couple of problems in your code. First of all, why convert Actions to a list if you are going to map each action right after that? So, the first fix is to remove that ToList() call:

var actionIds = formFields
  .Select(x => x.GridDefinition.Actions.Select(y => y.DFActionID).ToList())
  .ToList();

Then the second improvement comes, which stems from the fundamental question - what do you want to get in the end? Are all those items in all the separate lists the same, and should be placed into a single list? If so, then you need to use the SelectMany() operator, which, again, does not require the intermediate ToList() since the final ToList() will collect all the items anyway:

var actionIds = formFields
  .SelectMany(x => x.GridDefinition.Actions.Select(y => y.DFActionID))
  .ToList();
  • Related