我有两个通过 LINQ 返回的列表。我的目标是返回“默认”列表中的所有项目减去“notDefaults”列表中的所有项目。
我目前正在通过两个嵌套的 for 循环并使用“RemoveAt”来执行此操作。这可以只用一个 LINQ 语句来完成吗?基本上,我需要“默认”列表中的所有内容,除非该项目存在于“AssetPayrollMarkupOverrides”表中。
我很担心使用“RemoveAt”,因为它看起来很慢。
var defaults = (from a in dbcontext.Assets
join b in dbcontext.AssetAddresses on a.AssetID equals b.AssetID
join c in dbcontext.Addresses on b.AddressID equals c.AddressID
join d in dbcontext.StateLookups on c.StateID equals d.StateID
where d.ShortName == state
select new AssetMarkup()
{
AssetId = a.AssetID,
AssetName = a.AssetName,
Seg1_Code = a.Seg1_Code,
}).ToList();
var notDefaults = (from a in dbcontext.Assets
join b in dbcontext.AssetAddresses on a.AssetID equals b.AssetID
join c in dbcontext.Addresses on b.AddressID equals c.AddressID
join d in dbcontext.StateLookups on c.StateID equals d.StateID
join e in dbcontext.AssetPayrollMarkupOverrides on a.AssetID equals e.AssetID
where d.ShortName == state
select new AssetMarkup()
{
AssetId = a.AssetID,
AssetName = a.AssetName,
Seg1_Code = a.Seg1_Code,
ShortName = d.ShortName,
OfficePercentage = e.OfficePercentage,
MaintenancePercentage = e.MaintenancePercentage,
Note = e.Note
}).ToList();
我最初采用这种方式来确保两个列表匹配:
var defaults = (from a in dbcontext.Assets
join b in dbcontext.AssetAddresses on a.AssetID equals b.AssetID
join c in dbcontext.Addresses on b.AddressID equals c.AddressID
join d in dbcontext.StateLookups on c.StateID equals d.StateID
where d.ShortName == state
select new AssetMarkup()
{
AssetId = a.AssetID,
AssetName = a.AssetName,
Seg1_Code = a.Seg1_Code,
ShortName = d.ShortName,
OfficePercentage = dbcontext.PayrollMarkups.Where(x => x.StateID == c.StateID).Select(x => x.OfficePercentage).FirstOrDefault(),
MaintenancePercentage = dbcontext.PayrollMarkups.Where(x => x.StateID == c.StateID).Select(x => x.MaintenancePercentage).FirstOrDefault(),
Note = dbcontext.AssetPayrollMarkupOverrides.Where(x => x.AssetID == a.AssetID).Select(x => x.Note).FirstOrDefault()
}).ToList();
var notDefaults = (from a in dbcontext.Assets
join b in dbcontext.AssetAddresses on a.AssetID equals b.AssetID
join c in dbcontext.Addresses on b.AddressID equals c.AddressID
join d in dbcontext.StateLookups on c.StateID equals d.StateID
join e in dbcontext.AssetPayrollMarkupOverrides on a.AssetID equals e.AssetID
where d.ShortName == state
select new AssetMarkup()
{
AssetId = a.AssetID,
AssetName = a.AssetName,
Seg1_Code = a.Seg1_Code,
ShortName = d.ShortName,
OfficePercentage = dbcontext.PayrollMarkups.Where(x => x.StateID == c.StateID).Select(x => x.OfficePercentage).FirstOrDefault(),
MaintenancePercentage = dbcontext.PayrollMarkups.Where(x => x.StateID == c.StateID).Select(x => x.MaintenancePercentage).FirstOrDefault(),
Note = dbcontext.AssetPayrollMarkupOverrides.Where(x => x.AssetID == a.AssetID).Select(x => x.Note).FirstOrDefault()
}).ToList();
return Json(defaults.Except(notDefaults).OrderBy(x => x.AssetName).ToDataSourceResult(request));