【问题标题】:how to add item in list which is generated by query [closed]如何在查询生成的列表中添加项目[关闭]
【发布时间】:2026-01-19 14:15:02
【问题描述】:

这是我的清单,我想在其中添加一条额外的记录...................... .....

var foremandata = (from f in db.mqTimeReportingTimeLogs
                               join e in db.mqEmployeeMasters on f.tlEmployeeId equals e.empId
                               join c in db.mqCraftCodeMasters on f.tlCraftId equals c.craftCodeId
                               where f.tlJobId == jobid && f.tlCompanyId == compId && f.tlWeekEnding == weekend

                               select new
                               {
                                   EmpNum = e.empnum,
                                   EmployeeName = e.empName,
                                   DateWorked = f.tlDateWorked,
                                   CraftCode = c.craftCode,
                                   CCID = f.tlCraftId,
                                   STime = f.tlStraightTime,
                                   OTime = f.tlOT
                               }).OrderBy(x => x.EmployeeName).ToList();

【问题讨论】:

  • 只需将其设为调用ToList 的列表并使用list.Add() 添加项目:foremandata.Add(whatever)
  • 既然您已经完成ToList(),您可以使用foremandata.Add() 获取新数据或使用foremandata.AddRange() 获取具有相同类型的现有列表,具体取决于上下文。

标签: c# .net asp.net-mvc entity-framework


【解决方案1】:

我建议您构建一个强类型 DTO 类,而不是投影到匿名类型,该类包含查询结果投影所需的所有属性。下面是一个 DTO 类的例子:

public class EmployeeDTO
{
    public int EmpNum { get; set; }
    public string EmployeeName { get; set; }
    public DateTime DateWorked { get; set; }
    public string CraftCode { get; set; }
    public int CCID { get; set; }
    public DateTime STime { get; set; }
    public DateTime OTime { get; set; }
}

然后您可以将该类用作查询的投影目标:

var foremandata = (from f in db.mqTimeReportingTimeLogs
                   join e in db.mqEmployeeMasters on f.tlEmployeeId equals e.empId
                   join c in db.mqCraftCodeMasters on f.tlCraftId equals c.craftCodeId
                   where f.tlJobId == jobid && f.tlCompanyId == compId && f.tlWeekEnding == weekend

                   select new EmployeeDTO
                   {
                        EmpNum = e.empnum,
                        EmployeeName = e.empName,
                        DateWorked = f.tlDateWorked,
                        CraftCode = c.craftCode,
                        CCID = f.tlCraftId,
                        STime = f.tlStraightTime,
                        OTime = f.tlOT
                   }).OrderBy(x => x.EmployeeName).ToList(); // returns List<EmployeeDTO>

然后您可以使用该 DTO 类使用 Add()AddRange() 方法添加新项目,具体取决于您要添加的内容(单个数据或 List&lt;EmployeeDTO&gt;):

foremandata.Add(new EmployeeDTO()
{
    EmpNum = 1, // some value
    EmpName = "[employee name]",

    // other properties here
});

【讨论】: