Search code examples
c#linq

C# Removing a List from a List


Is there a convenient way to remove a nested list from another list if it meets certain requirements? For example, say we have a collection of stops, and we decide to call each collection of stops a route. Each route is in list from. Then we decide to put each route into a list as well.

So now that we have a list of routes, someone decides that certain types of routes really shouldn't be included in the route list. How can I remove those routes? Here's some sample code:

Example Class

public class Stops
{
    public Stops(int _param1, string _param2)
    {
        param1 = _param1;
        param2 = _param2;
    }

    public int param1 { get; set; }
    public string param2 { get; set; }
}

Create the Lists

List<List<Stops>> lstRoutes = new List<List<Stops>>();
List<Stops> lstStops = new List<Stops>();
List<Stops> lstMoreStops = new List<Stops>();

// Create some stops
for (int i = 0; i < 5; i++)
{
    lstStops.Add(new Stops(i, "some text"));
}

lstRoutes.Add(lstStops);

// Create some more stops
for (int i = 5; i < 10; i++)
{
    lstMoreStops.Add(new Stops(i, "some more text"));
}

lstRoutes.Add(lstMoreStops);

How can I remove any route from lstRoutes that has, say, any param1 value greater than 6?


Solution

  • The simplest way (which can be applicable to all enumerables, not just lists) would be:

    lstRoutes = lstRoutes.Where(r => !r.Any(s => s.param1 > 6)).ToList();
    

    The snippet above creates a new list, so copying will occur which means both the performance and memory usage will slightly suffer. The most efficient way would be not adding those items to the list in the first place.

    The second most efficient way would be to remove items from the list instead of constructing a new one, so the memory usage wouldn't be affected as much:

    lstRoutes.RemoveAll(r => r.Any(s => s.param1 > 6));