是否有可能以某种方式转换整个集合,而不是一个一个地进行?

问题描述 投票:0回答:1

是否有可能以某种方式转换整个集合,而不是一个一个地进行?

我经常遇到需要将列表中的元素从一种类型转换为另一种类型的情况。 我通常最终得到的解决方案是这样的

using System;
using System.Collections.Generic;
using System.Linq;

namespace ListProcessing
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
    }
    


    class Program
    {
        public static List<Employee> Hire(List<Person> persons)
        {
        var output = new List<Employee>();
        foreach(var p in persons)
        {
            var employee = new Employee { Id = p.Id, Name = p.Name, Position = "Software Engineer" };
        }
        
            return output;
        }
        static void Main(string[] args)
        {
            List<Person> persons = new List<Person>
            {
                new Person { Id = 1, Name = "John Doe", Department = "Software" },
                new Person { Id = 2, Name = "Jane Smith", Department = "Marketing" },
                new Person { Id = 3, Name = "Bob Johnson", Department = "Software" },
                new Person { Id = 4, Name = "Sally Jones", Department = "HR" }
            };

            //Attempt 1
            IEnumerable<Employee> employees = persons
                .Select(p => new Employee { Id = p.Id, Name = p.Name, Position = "Software Engineer" });

            //Attempt 2
            var employees2 = Hire(persons);

            foreach (Employee employee in employees)
            {
                Console.WriteLine($"ID: {employee.Id}, Name: {employee.Name}, Position: {employee.Position}");
            }
        }
    }
}

通过 linq 或将每个元素插入列表并返回它们来完成。

总是需要某种迭代,而事实上每个项目都必须执行相同的指令,这让我很烦恼..

我觉得这个问题可以从一开始就使用正确的类型来解决,或者可以实现某种重载机制 它不会迭代它们,但基本上将集合作为集合处理并返回“已处理”的相同集合 - 和 O(1) 操作。

c# batch-processing loop-unrolling
1个回答
0
投票

您可以像这样创建继承层次结构:

public abstract class Person
{
    public int Id { get; init; }
    public string Name { get; init; }

    public override string ToString() =>
        $"ID: {Id}, Name: {Name}";
}

public class NaturalPerson : Person
{
    public string Department { get; init; }

    public override string ToString() =>
        base.ToString() + $", Department: {Department}";
}

public class Employee : Person
{
    public string Position { get; init; }

    public override string ToString() =>
        base.ToString() + $", Position: {Position}";
}

请注意,由于

Person
类是抽象类,因此您无法实例化它;但是,您可以声明一个
List<Person>
并添加两个派生类的对象。

© www.soinside.com 2019 - 2024. All rights reserved.