【发布时间】:2013-02-19 01:35:44
【问题描述】:
我想要一个List<Container>,其中Container.Active == true 只给我containerObject.Items > 2。如何以这种方式过滤子列表?
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
}
}
}
}
}
我不应该在注明的地方打印任何小于 2 的值。
【问题讨论】:
-
你的意思是容器的长度应该> 2?
-
我的意思是
Items中的每个int应该> 2。任何小于2 的都应该删除。 -
我起初以为你的意思是你想要一个从索引 2 开始的子列表,因为这就是你在标题中所说的。如果是这种情况,您将使用
containers.Skip(2).Where(c => c.Active)。 -
这道题是西方最快枪问题的经典案例
标签: c# .net linq filter sublist