我有一个类结构如下(每个子类可以有任意数量,也可以有多个Masters)。我想使用linq查询来获取Subfolios的扁平列表,并按Subfolio的“Index”属性进行过滤。
我想我可以使用以下方法获取Master的子文件夹:
IEnumerable< Subfolio> result = from dd in devices.Master
where dd.ID == 14
from pfo in dd. Portfolio
from folio in pfo.Folio
from subfolio in folio.Subfolio
where subfolio.Ind == 32
select subfolio;
或者
IEnumerable<Subfolio> result =
devices.master.Where(x => x.ID == 14)
.SelectMany(y => y.PFO)
.SelectMany(z => z.Folio)
.SelectMany(a => a.Subfolio)
.Where(b=>b.Ind==32);
我可以为每个slave做同样的事情并将结果与Master查询结合起来,但有一种方法可以在一个linq操作中执行此操作。目前我正在使用一大堆foreach循环,非常笨重。
简化的类结构是:
Devices
Master
Portfolio
Folio
Subfolio
Subfolio
Folio
Subfolio
Subfolio
Subfolio
Portfolio
Folio
Subfolio
Subfolio
Folio
Subfolio
Subfolio
Subfolio
Slave
Portfolio
Folio
Subfolio
Subfolio
Folio
Subfolio
Subfolio
Subfolio
Portfolio
Folio
Subfolio
Subfolio
Folio
Subfolio
Subfolio
Subfolio
Slave
Portfolio
Folio
Subfolio
Subfolio
Folio
Subfolio
Subfolio
Subfolio
Portfolio
Folio
Subfolio
Subfolio
Folio
Subfolio
Subfolio
Subfolio
答案 0 :(得分:1)
不确定此代码是否可行(测试需要时间),但是这样的事情应该可以解决问题:
var resultMaster = devices.Master.SelectMany(y => y.PFO);
var resultSlave = devices.Slave.SelectMany(y => y.PFO);
var result = resultMaster.Union(resultSlave)
.SelectMany(z => z.Folio)
.SelectMany(a => a.Subfolio)
.Where(b=>b.Ind==32);
可读性有3个部分,但查询将作为一个执行。
答案 1 :(得分:0)
除此之外,这是我的完整解决方案(我没有说明Slaves是Masters的子类)
public nF GetValuebyuNidIndex(dev devices, UInt32 MuNID, ushort nFIndex)
{
var result_m = devices.wNode.Where(p => p.uNID == MuNID)
.SelectMany(x => x.PFO);
var result_s = devices.wNode.Where(p => p.uNID == MuNID)
.SelectMany(x => x.sNode)
.SelectMany(x => x.PFO);
var combined = result_m.Union(result_s)
.SelectMany(x => x.Folio)
.SelectMany(x => x.nF)
.Where(x => x.Ind == nFIndex);
return combined.FirstOrDefault();
}
这也有效。据推测,它编译成同样的东西?
public nF GetValuebyuNidIndex1(dev devices, UInt32 MuNID, ushort nFIndex)
{
var result_m = from dd in devices.wNode
where dd.uNID == MuNID
from pfo in dd.PFO
select pfo;
var result_s = from dd in devices.wNode
where dd.uNID == MuNID
from snode in dd.sNode
from pfo in snode.PFO
select pfo;
var combined = result_m.Union(result_s);
var result = from cc in combined
from ff in cc.Folio
from nn in ff.nF
where nn.Ind == nFIndex
select nn;
return result.FirstOrDefault();
}