I want a List<Container>
where Container.Active == true
and give me only containerObject.Items > 2
. How can I filter the sublist in 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 where noted.
Try this:
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);
Try:
var result = containers.Where(c => c.Active && c.Items.Count() > 2);
If you don't really need to do it in a single query:
var result = containers.Where(c => c.Active).ToList();
result.ForEach(c => c.Items.RemoveAll(i => i <= 2));
From your feedback, I presume that you're looking for a query like this:
var result = containers
.Where(c => c.Active)
.Select(c => new Container(c.Active, c.Items.Where( i => i>2).ToArray()));
it makes copies of the containers, except it filters out the items which are not greater than 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With