【问题标题】:How to filter a sublist of items如何过滤项目的子列表
【发布时间】: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 =&gt; c.Active)
  • 这道题是西方最快枪问题的经典案例

标签: c# .net linq filter sublist


【解决方案1】:

试试:

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

【讨论】:

  • @Downvoter - 想发表评论?我已经编辑了我的帖子以适应 OP 的更新答案。
  • 即使您进行了编辑,这也不起作用。 OP 希望内部列表不包含小于 2 的项目。这将返回仍然为 0,1 的容器
【解决方案2】:

您必须创建一个新的Container。除非您想更改现有的(如果您需要,我会添加该代码)

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);

如果所有项目都被过滤掉,最后一行确保不返回。

【讨论】:

  • 我已经更新了我的答案,以反映我认为您正在寻找的内容
【解决方案3】:

试试这个:

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

标准格式:

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

【讨论】:

【解决方案4】:

根据您的反馈,我推测您正在寻找这样的查询:

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

它会复制容器,但它会过滤掉不大于 2 的项目

【讨论】:

  • 后一个版本有效。第一个没有结果。
  • @P.Brian.Mackey 没有一个容器真正满足第一个版本,因为它们都包含至少一个小于2 的项目我认为第二个版本或多或少是什么你在找吗?
【解决方案5】:

如果您真的不需要在单个查询中执行此操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2015-06-04
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多