如何在 LINQ 列表中添加新记录
本文关键字:添加 新记录 列表 LINQ | 更新日期: 2023-09-27 18:35:23
我使用了q Linq查询并在列表索引顶部添加了一条新记录
List<PMAST> lstPmast = new List<PMAST>();
lstPmast.Add(new PMAST() { EmpId = 0, PCODE = "--Select--", PNAME = "--Select--" });
var GetEmployeeLst = (from d in db.PMASTs
where d.CNO == iCNO && d.Isdeleted != true
select new
{
EmpId = d.EmpId,
PCODE = d.PCODE,
PNAME = d.PNAME
}).ToList();
您可以通过
多种方式做到这一点,其中一种只是使用AddRange
List
方法:
List<PMAST> lstPmast = new List<PMAST>();
lstPmast.Add(new PMAST() { EmpId = 0, PCODE = "--Select--", PNAME = "--Select--" });
var GetEmployeeLst = (from d in db.PMASTs
where d.CNO == iCNO && d.Isdeleted != true
select new
{
EmpId = d.EmpId,
PCODE = d.PCODE,
PNAME = d.PNAME
}).ToList();
lstPmast.AddRange(GetEmployeeLst);
由于您的问题被标记为 MVC ASP.NET,我假设您正在尝试在下拉列表中添加一些默认值。如果是这种情况,您可以直接使用适当的DropDownListFor
助手,它允许您实现这一点,而无需在视图模型中插入此类假记录:
@Html.DropDownListFor(x => x.SelectedEmployee, Model.Employees, "--Select--")
您不再需要更改数据模型来实现这种纯粹的 UI 内容。
使用 this 而不是 Add:
lstPmast.Insert(0,new PMAST() { EmpId = 0, PCODE = "--Select--", PNAME = "--Select--" });
您可以通过列表添加 ne 记录。
lstPmast.add(newlistitem);
看起来您的对象列表最终将出现在 asp.net 组合框或 winform 组合框中。
这是我的建议
List<Tuple<int,string>> lstPmast;
var lstPmast = db.PMASTs.Where(d => d.CNO == iCNO && !d.Isdeleted).Select(d => Tuple.Create(d.EmpId, e.PCODE + "-" + e.PNAME)).ToList();
// then add a default as the first item in the list
lstPmast.Insert(0, Tuple.Create(0, "--- Select ---"));
// bind the list to your combobox here. Use Item1 as value and Item2 as the description