3

I am a list of lists with the same type of objects and I am trying to convert it to a single list with all the 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 am using twice Any on it which is quite bad for efficiency. It would be much better if it was a simple list.

2
  • I see you're also doing a Where(area => area != null). Do you have null elements as well? I'll update my answer if so. Commented Aug 5, 2014 at 7:47
  • Why do you think using Any twice is "quite bad for efficiency"? Commented Aug 5, 2014 at 7:47

2 Answers 2

16

You can do:

var allTrackAreasCombined = allTrackAreas.SelectMany(t => t).ToList();
Sign up to request clarification or add additional context in comments.

Comments

0

If you have list of list like this

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

so you can make all Records in single list like using this code

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

then in test you got all six records.

I hope this help you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.