Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a sublist of items

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.

like image 731
P.Brian.Mackey Avatar asked Mar 04 '13 20:03

P.Brian.Mackey


4 Answers

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);
like image 124
Parimal Raj Avatar answered Nov 03 '22 01:11

Parimal Raj


Try:

var result = containers.Where(c => c.Active && c.Items.Count() > 2);
like image 28
Darren Avatar answered Nov 03 '22 02:11

Darren


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));
like image 28
aush Avatar answered Nov 03 '22 02:11

aush


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

like image 41
Sam I am says Reinstate Monica Avatar answered Nov 03 '22 01:11

Sam I am says Reinstate Monica