我正在尝试编写一个 Linq 查询,它可以从父产品的外部集合中连接内部标签集合,并返回一个标签集合,其合并计数按计数降序排列。
这是我目前拥有的一个工作解决方案,正在寻求转换为单个 Linq 查询的帮助。
Module Module1
Class Tag
Property Name As String
Property Count As Integer
End Class
Class Product
Property Name As String
Property tags As List(Of Tag)
End Class
Sub Main()
Dim Products As New List(Of Product) From {
{New Product With {.Name = "P1",
.tags = New List(Of Tag) From {{New Tag With {.Name = "T1"}},
{New Tag With {.Name = "T3"}},
{New Tag With {.Name = "T5"}}
}
}
},
{New Product With {.Name = "P2",
.tags = New List(Of Tag) From {{New Tag With {.Name = "T2"}},
{New Tag With {.Name = "T4"}},
{New Tag With {.Name = "T6"}}
}
}
},
{New Product With {.Name = "P3",
.tags = New List(Of Tag) From {{New Tag With {.Name = "T2"}},
{New Tag With {.Name = "T3"}},
{New Tag With {.Name = "T4"}}
}
}
},
{New Product With {.Name = "P4",
.tags = New List(Of Tag) From {{New Tag With {.Name = "T4"}},
{New Tag With {.Name = "T5"}},
{New Tag With {.Name = "T6"}},
{New Tag With {.Name = "T7"}},
{New Tag With {.Name = "T8"}}
}
}
}
}
Dim ReportingTags As New List(Of Tag)
'-- Start : Needs to be converted to pure Linq (if possible)------------------------------------------
Dim InterimTags As New List(Of String)
For Each p As Product In Products
Dim TmpTags As New List(Of String)
InterimTags.AddRange(TmpTags.Concat(From t In p.tags Select t.Name))
Next
ReportingTags.AddRange((From t In InterimTags
Group By name = t Into Count = Count()
Select New Tag With {.Name = name,
.Count = Count}).OrderByDescending(Function(t) t.Count))
'-- End ----------------------------------------------------------------------------------------------
For Each t As Tag In ReportingTags
Console.WriteLine("Tag: {0} - Count: {1}", t.Name, t.Count)
Next
Console.ReadLine()
End Sub
端模块
我将获取输出并将其转换为 observablecollection(of TagModel) - 所以我试图消除对数据的双重/三重处理。
谢谢
格雷姆