我有一个像这样的表
Id TagNo FromBay FromPanel FDevice FRef
1 1000 A B C1 1
2 1000 A B C1 2
3 1000 A B C1 R2
4 1000 A B C2 2
5 1000 A B C2 3
6 1000 A B C2 4
我想要这个
TagNo FromBay FromPanel FDevice FRef
1000 A B C1 1
2
R2
C2 2
3
4
值位于名为cableDataTable
的DataTable中 var rows = cableDataTable.AsEnumerable()
.Select(x => new
{
TagNo = x.Field<string>("TagNo"),
FromBay = x.Field<string>("FromBay"),
FromPanel = x.Field<string>("FromPanel"),
FDevice = x.Field<string>("FDevice"),
FRef = x.Field<string>("FRef")
});
var results = rows.GroupBy(row => new { row.FromBay, row.FromPanel, row.TagNo })
.OrderBy(g => g.Key.FromBay)
.ThenBy(g => g.Key.FromPanel)
.SelectMany(g => g.OrderBy(row => row.TagNo)
.Select((x, i) =>
new
{
TagNo = (i == 0) ? x.TagNo.ToString() : "",
FromBay = (i == 0) ? x.FromBay : "",
FromPanel = (i == 0) ? x.FromPanel : "",
FDevice = (i == 0) ? x.FDevice : "",
FRef = x.FRef,
})).ToList();
但我得到了这个
TagNo FromBay FromPanel FDevice FRef
1000 A B C1 1
2
R2
2
3
4
我在一个论坛中发现了这个,但我不知道是什么。选择((x,i)兴奋地做,我怎样才能得到我需要的结果。 我找不到问题
答案 0 :(得分:0)
我给你写了一个以分层方式获取数据的例子,我希望这是你正在寻找的。 p>
var results = rows.GroupBy(row => new {row.FromBay, row.FromPanel, row.TagNo})
.Select(x => new
{
x.Key.TagNo,
x.Key.FromBay,
x.Key.FromPanel,
Devices =
rows.GroupBy(
row => new {row.FromBay, row.FromPanel, row.TagNo, row.FDevice})
.Where(f => f.Key.TagNo == x.Key.TagNo)
.Where(f => f.Key.FromBay == x.Key.FromBay)
.Where(f => f.Key.FromPanel == x.Key.FromPanel)
.Select(y => new
{
y.Key.FDevice,
FRef =
rows.Where(r => r.TagNo == y.Key.TagNo)
.Where(r => r.FromBay == y.Key.FromBay)
.Where(r => r.FromPanel == y.Key.FromPanel)
.Where(r => r.FDevice == y.Key.FDevice)
.Select(i => i.FRef)
.ToList()
}).ToList()
}).ToList();
答案 1 :(得分:0)
试试这个:
var results = rows.GroupBy(row => new { row.TagNo, row.FromBay, row.FromPanel})
.OrderBy(g => g.Key.TagNo)
.ThenBy(g => g.Key.FromBay)
.ThenBy(g => g.Key.FromPanel)
.Select((g,i) => new {
key = g.Key,i,
sub = g.GroupBy(x=>x.FDevice).OrderBy(g=>g.Key)
.Select(g=>g.Select((x,j)=>new{x,j}))
})
.SelectMany(e=> e.sub, (e,c)=> new {
TagNo = e.i == 0 ? e.key.TagNo.ToString() : "",
FromBay = e.i == 0 ? e.key.FromBay : "",
FromPanel = e.i == 0 ? e.key.FromPanel : "",
FDevice = c.j == 0 ? c.x.FDevice : "",
FRef = c.x.FRef,
});