从子列表中选择n项?

时间:2018-04-23 05:38:29

标签: c# .net list linq

如何获取子列表的N个元素?假设我想为每个父母分别生两个孩子。

public class Program
{
    static void Main(string[] args)
    {
        var data = new List<Parent>()
        {
            new Parent()
            {
                Id = 1,
                Name = "ParentName1",
                Children = new List<Child>()
                {
                    new Child() { Id = 1, Name = "ChildName1"},
                    new Child() { Id = 2, Name = "ChildName2"},
                    new Child() { Id = 3, Name = "ChildName3"},
                    new Child() { Id = 4, Name = "ChildName4"},
                    new Child() { Id = 5, Name = "ChildName5"},
                }
            },
            new Parent()
            {
                Id = 2,
                Name = "ParentName2",
                Children = new List<Child>()
                {
                    new Child() { Id = 6, Name = "ChildName6"},
                    new Child() { Id = 7, Name = "ChildName7"},
                    new Child() { Id = 8, Name = "ChildName8"},
                    new Child() { Id = 9, Name = "ChildName9"},
                    new Child() { Id = 10, Name = "ChildName10"},
                }
            }
        };

        // Get only 2 child elements for parent
        var filteredData = data.Where(x => x.Children.Count >= 2)
            .ToList();


        foreach (var filteredParent in filteredData)
        {
            Console.WriteLine($"Parent {filteredParent.Id} with {filteredParent.Children.Count} children.");
        }

        Console.ReadKey();
    }
}

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Parent Parent { get; set; }
}

1 个答案:

答案 0 :(得分:1)

一种方法是对结果选择器和List<T>的{​​{1}}方法使用多语句lambda表达式:

RemoveRange

正如Flater评论的那样,最好只返回父亲的浅拷贝,只有前两个孩子。这样您的查询就不会更改源数据:

var query = data.Select
(
    p => 
    {
        p.Children.RemoveRange(2, p.Children.Count - 2); 
        return p;
    }
);