Converting a list of lists to one list using linq

I am a list of lists with the same object type and I am trying to convert it to one list with all objects using linq.

How can i do this?

This is my current code:

  var allTrackAreas =
            _routables.Select(
                routable =>
                    _centrifugeHelper.GetTrackAreasFromRoutable(routable, _trackAreaCutterParameters,
                        _allowedDestination.MatchedAreas[routable]))
                .Where(area => area != null).ToList();

        foreach (var testAction in _trackAreaCutterParameters.ConcurrentBagTestActions)
        {
            if (allTrackAreas.Any(areas => areas.Any(area => area.Id == testAction.TrackAreaId)))
            {
                currentActions.Add(testAction);
            }
        }

      

The variable allTrackAreas is a list of lists and I use Any twice which is bad for efficiency. It would be much better if it were a simple list.

+3


source to share


2 answers


You can do:



var allTrackAreasCombined = allTrackAreas.SelectMany(t => t).ToList();

      

+13


source


If you have a list box like this

list[0]
      Records1[0]
      Records2[1]
      Records3[2]
list[1]
      Records1[0]
      Records2[1]
      Records3[2]

      

so you can make all entries in one list, for example using this code



list<object> test = new list<object>();
foreach(object items in list)
{
  foreach(object item in items)
  {
     test.add(item);
  }
}

      

then in the test you got all six records.

Hope this helps you.

0


source







All Articles