我的LINQ查询:
Dim groupedData = (From p In pData _
Group By p.TruncParam Into Group) _
.SelectMany(Function(g) g.Group) _
.Select(Function(d, idx) New With { _
.NewParameter = String.Concat(If(d.TruncParam.Length < 5, d.TruncParam, d.TruncParam.Substring(0, 5)), idx.ToString("0000")), _
.FullParameter = String.Format("{0}-{1} [{2}] <{3}>", d.LabName, d.TestName, d.Parameter, d.Unit)})
产生以下结果:
ID: SOLUB0000 Name: 001-AMT SOLUBL [SOLUBLES] <%>
ID: SOLUB0001 Name: CHEM-C4:SOL [SOLUBLES] <%>
ID: SOLUB0002 Name: CHEM-EMCARB:SOL [SOLUBLES] <%>
ID: INSOL0003 Name: 001-AMT:INSOL [INSOLUBLES] <%>
ID: INSOL0004 Name: CHEM-AMT:INSOL [INSOLUBLES] <%>
ID: INSOL0005 Name: CHEM-W:INSOL [INSOLUBLES] <%>
ID: INSOL0006 Name: CHEM-W:INSOL [INSOLUBLES] <mg/l>
ID: CLRES0007 Name: 001-CL RESIDUE [CL RESIDUE] <ppm>
ID: SUMCA0008 Name: 001-ELEMENTS [SUM CA K NA SI] <%>
ID: SUMME0009 Name: 001-ELEMENTS [SUM METALS + P] <%>
当TruncParam
更改时,我希望idx
子句中的索引(Select
)重置为1.因此,在上面的列表中,索引应为{{ 1}},SOLUB0001
,SOLUB0002
,INSOL0001
... INSOL0002
,CLRES0001
,SUMCA0001
。
我应该如何改变LINQ查询?
答案 0 :(得分:1)
您需要在SelectMany
语句(g.Group.Select(d, idx) => new {d, idx}
)中移动索引选择,如下所示:
Dim groupedData = (From p In pData _
Group By p.TruncParam Into Group) _
.SelectMany(Function(g) g.Group.Select(Function(d, idx) New With { _
.Element = d, .Index = idx}) _
.Select(Function(d) New With { _
.NewParameter = String.Concat(If(d.Element.TruncParam.Length < 5, d.Element.TruncParam, d.Element.TruncParam.Substring(0, 5)), d.Index.ToString("0000")), _
.FullParameter = String.Format("{0}-{1} [{2}] <{3}>", d.Element.LabName, d.Element.TestName, d.Element.Parameter, d.Element.Unit)})