繁体   English   中英

从列表对象的列表字段中删除元素的最佳方法

[英]Best way to remove elements from list field of list objects

我有对象建模文件和用户:

public class File
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public uint Size { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<File> Files { get; set; }
}

我创建了模型的对象列表:

var users = new List<User> { new User
            {
                Id = 1,
                Name = "Alex",
                Files = new List<File>
                {
                    new File
                    {
                        Id = 1,
                        Name = "123.txt",
                        Size = 20000
                    }
                    new File
                    {
                        Id = 3,
                        Name = "111.txt",
                        Size = 10
                    }
                }
            },
            new User
            {
                Id = 2,
                Name = "Andry",
                Files = new List<File>
                {
                    new File
                    {
                        Id = 1,
                        Name = "file.txt",
                        Size = 3
                    },
                    new File
                    {
                        Id = 2,
                        Name = "file.mp3",
                        Size = 4342
                    }
                }
            },
            new User
            {
                Id = 3,
                Name = "Jon",
                Files = new List<File>
                {
                    new File
                    {
                        Id = 1,
                        Name = "site.txt",
                        Size = 3324
                    }
                }
            },
        };

名称字段 - 对象用户列表文件包含对象列表文件。

如何删除Size <= 10的用户文件?

这种方式不起作用: users.SelectMany(u => u.Files).ToList().RemoveAll(f => f.Size <= 10);

LINQ是一种查询源的技术,而不是修改它们。 因此,您不应该使用查询并更改此查询中的内容。 相反,您可以过滤需要修改的内容,然后使用循环来实际应用更改。

IEnumerable<User> usersWithSmallFiles = users
    .Where(u => u.Files.Any(f => f.Size <= 10));

foreach (User u in usersWithSmallFiles)
    u.Files = u.Files.Where(f => f.Size > 10).ToList();

你也不能在IEnumerable<T>上使用RemoveAll ,它是一个List<T> -method。 这就是你在查询中使用ToList()的原因。 但是通过这种方式你创建了一个与你的Files -list无关的新列表,它只包含相同的文件,但是集合是不同的,所以RemoveAll是没有意义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM