How to filter a list of items

I want a List<Container> where Container.Active == true and give only containerObject.Items > 2 . How can I filter the sublist this way?

 using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { internal class Container { public List<int> Items { get; set; } public bool Active { get; set; } public Container(bool active, params int[] items) { Items = items.ToList(); Active = active; } } class Program { static void Main(string[] args) { var containers = new List<Container> {new Container(true,1, 2, 3), new Container(false, 1,2,3,4,5,6), new Container(true,1,2,5,6,7,8,9,10)}; var result = containers.Where(c => c.Active); foreach (var container in result) { foreach (var item in container.Items) { Console.WriteLine(item);//I should not print any values less than two here } } } } } 

I should not print any values ​​less than two, if indicated.

+4
source share
5 answers

Try the following:

 var result = from container in containers.Where(c => c.Active) from item in container.Items where item > 2 select container; 

In standard form:

 var standard_result = containers .Where(container => container.Active && container.Items.All(i => i > 2)) .SelectMany(con => con.Items); 
+8
source

Try:

 var result = containers.Where(c => c.Active && c.Items.Count() > 2); 
+4
source

You will need to create a new Container . If you do not want to modify the existing one (I will add this code if this is what you need)

 var result = containers.Where(c => c.Active) .Select(c=>new Container(c.Active, c.Select(i=>i>2).ToArray())) .Select(c=>c.Items.Count > 0); 

The last row will not be returned if all elements are filtered out.

+2
source

From your reviews, I assume you are looking for the following query:

 var result = containers .Where(c => c.Active) .Select(c => new Container(c.Active, c.Items.Where( i => i>2).ToArray())); 

it makes copies of containers, except that it filters out elements that do not exceed 2

+2
source

If you really do not need to do this in one request:

 var result = containers.Where(c => c.Active).ToList(); result.ForEach(c => c.Items.RemoveAll(i => i <= 2)); 
+2
source

All Articles