我一直在尝试开发一个linq查询,它返回数据库中所有表的ItemNumber列,但到目前为止我还没能成功完成.
基本上我有一个表用于计算机中的每种硬件组件,每个表都有一个ItemNumber列.我需要在一个爆炸中查询所有表,并在平面列表/数组中返回ItemNumber值.(基本上我希望能够做到以下)
foreach (var c in items) { Console.WriteLine(c.ItemNumber); }
搜索网无济于事,有人能告诉我一个如何做到这一点的例子吗?我最好的尝试是以下,但我不明白Sql足以实现这一目标.
var items = from hc in dc.DataBoxPCHardwareCases from hhd in dc.DataBoxPCHardwareHardDrives from hkb in dc.DataBoxPCHardwareKeyboards from hmm in dc.DataBoxPCHardwareMemories from hmo in dc.DataBoxPCHardwareMonitors from hmb in dc.DataBoxPCHardwareMotherboards from hms in dc.DataBoxPCHardwareMouses from hod in dc.DataBoxPCHardwareOpticalDrives from hps in dc.DataBoxPCHardwarePowerSupplies from hpc in dc.DataBoxPCHardwareProcessors from hsp in dc.DataBoxPCHardwareSpeakers from hvc in dc.DataBoxPCHardwareVideoCards from sos in dc.DataBoxPCSoftwareOperatingSystems select new { hc, hhd, hkb, hmm, hmo, hmb, hms, hod, hps, hpc, hsp, hvc, sos };
Rex M.. 5
你所描述的是一个联盟:
SELECT ItemNumber FROM tbl1 UNION SELECT ItemNumber FROM tbl2
在LINQ中:
var itemCounts = (from hhd in dc.HHD select hhd.ItemNumber) .Union((from hkb in dc.HKB select hkb.ItemNumber) .Union(from hmm in dc.HMM select hmm.ItemNumber)) and so on
请注意,使用这样的UNION并不是非常有效.您将整个数据集一次性地传输到数据库,但数据库服务器必须为每个UNION执行单独的查询,因此如果您计划针对大量数据执行复杂操作,那么您最好重新考虑你的数据库设计.
你所描述的是一个联盟:
SELECT ItemNumber FROM tbl1 UNION SELECT ItemNumber FROM tbl2
在LINQ中:
var itemCounts = (from hhd in dc.HHD select hhd.ItemNumber) .Union((from hkb in dc.HKB select hkb.ItemNumber) .Union(from hmm in dc.HMM select hmm.ItemNumber)) and so on
请注意,使用这样的UNION并不是非常有效.您将整个数据集一次性地传输到数据库,但数据库服务器必须为每个UNION执行单独的查询,因此如果您计划针对大量数据执行复杂操作,那么您最好重新考虑你的数据库设计.
不要使用Union - 而是使用Concat!
LinqToSql的Union映射到T-Sql的Union.
LinqToSql的Concat映射到T-Sql的Union All.
不同之处在于Union要求相互检查列表并删除重复项.这种检查需要花费时间,我希望你的零件编号在全球范围内是唯一的(仅出现在一个列表中). Union All跳过此额外检查和重复删除.
ListitemNumbers = dc.DataBoxPCHardwareCases.Select(hc => hc.ItemNumber) .Concat(dc.DataBoxPCHardwareHardDrives.Select( hkd => hkd.ItemNumber )) .Concat(dc.DataBoxPCHardwareKeyboards.Select( hkb => hkb.ItemNumber )) .Concat(dc.DataBoxPCHardwareMemories.Select( hhh => hhh.ItemNumber )) .Concat(dc.DataBoxPCHardwareMonitors.Select( hmo => hmo.ItemNumber )) .Concat(dc.DataBoxPCHardwareMotherboards.Select( hmb => hmb.ItemNumber )) .Concat(dc.DataBoxPCHardwareMouses.Select( hms => hms.ItemNumber )) .Concat(dc.DataBoxPCHardwareOpticalDrives.Select( hod => hod.ItemNumber )) .Concat(dc.DataBoxPCHardwarePowerSupplies.Select( hps => hps.ItemNumber )) .Concat(dc.DataBoxPCHardwareProcessors.Select( hpc => hpc.ItemNumber )) .Concat(dc.DataBoxPCHardwareSpeakers.Select( hsp => hsp.ItemNumber )) .Concat(dc.DataBoxPCHardwareVideoCards.Select( hvc => hvc.ItemNumber )) .Concat(dc.DataBoxPCSoftwareOperatingSystems.Select( sos => sos.ItemNumber )) .ToList();