You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不循环的情况下将EmployeeList转换为NewsFeedEmployees列表?

问题描述

我有一个EmployeeList类型的用户列表,类定义如下:

public class EmployeeList
{
    public int Emp_No { get; set; }
    public string Sys_Prefix { get; set; }
    public short Company_No { get; set; }
    public string Surname { get; set; }
    public string First_Name { get; set; }
    public string Known_As { get; set; }
    public string Initials { get; set; }
    public string Title { get; set; }
}

需要将该列表内容转换到新列表var newsFeedEmps = new List<NewsFeedEmployees>();中,NewsFeedEmployees类定义如下:

public partial class NewsFeedEmployees
{
    public long Company_No { get; set; }
    public long Emp_No { get; set; }
    public long SourceId { get; set; }
    public string Sys_Prefix { get; set; }

    public long NewsFeedID { get; set; }

    public bool isActive { get; set; }
}

由于两类属性不匹配,且需为所有转换后的对象统一设置NewsFeedID和isActive值,无法直接使用newsFeedEmps.AddRange(EmployeeList);同时不想通过foreach循环逐个添加对象。

曾尝试使用以下代码,但报错:Queue不包含EnqueueRange的定义

Queue<NewsFeedEmployees> myQueue = new Queue<NewsFeedEmployees>();
myQueue.EnqueueRange(emps.Select(emp => new NewsFeedEmployees()
{
    Company_No = emp.Company_No,
    Emp_No = emp.Emp_No,
}));
解决方案

方法1:利用List的AddRange结合LINQ转换

List<T>自带AddRange方法,可直接接收LINQ查询结果,无需手动循环。通过Select将每个EmployeeList对象转换为NewsFeedEmployees,同时统一设置公共属性,再添加到目标列表:

// 假设原列表名为employeeList
long targetNewsFeedID = 123; // 替换为你需要的统一值
bool targetIsActive = true; // 替换为你需要的统一值

newsFeedEmps.AddRange(employeeList.Select(emp => new NewsFeedEmployees
{
    Company_No = emp.Company_No, // short可隐式转换为long
    Emp_No = emp.Emp_No, // int可隐式转换为long
    Sys_Prefix = emp.Sys_Prefix,
    NewsFeedID = targetNewsFeedID,
    isActive = targetIsActive
    // SourceId若有默认值可忽略,或根据需求赋值
}));

方法2:直接生成目标List

如果无需保留初始空列表newsFeedEmps,可直接用ToList()生成目标列表,代码更简洁:

long targetNewsFeedID = 123;
bool targetIsActive = true;

var newsFeedEmps = employeeList.Select(emp => new NewsFeedEmployees
{
    Company_No = emp.Company_No,
    Emp_No = emp.Emp_No,
    Sys_Prefix = emp.Sys_Prefix,
    NewsFeedID = targetNewsFeedID,
    isActive = targetIsActive
}).ToList();

关于Queue的EnqueueRange问题

.NET内置的Queue<T>并没有EnqueueRange方法,你看到的代码要么是自定义扩展方法,要么来自第三方框架。若一定要用Queue,可先将转换后的集合转为数组再逐个入队,或自行实现扩展方法:

// 自定义Queue扩展方法
public static class QueueExtensions
{
    public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items)
    {
        foreach (var item in items)
        {
            queue.Enqueue(item);
        }
    }
}

不过该扩展方法内部仍使用foreach,本质和循环入队无区别,针对你的需求,List相关方案更直接高效。

内容的提问来源于stack exchange,提问作者Veronike Kitchen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:13:13