gpt4 book ai didi

c# - 如何过滤项目的子列表

转载 作者:太空狗 更新时间:2023-10-29 23:59:01 28 4
gpt4 key购买 nike

我想要一个 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
}
}
}
}
}

我不应该在注明的地方打印任何小于二的值。

最佳答案

试试这个:

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

关于c# - 如何过滤项目的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15210458/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com