1
我有數據列表如下圖所示如何使用LINQ分組和合並數據列表?
原始數據
Genre Name Year
Comedy Shrek Forever After 2010
Drama The Karate Kid 2010
Action Iron Man 2 2010
Action Robin Hood 2010
Drama The Kids Are All Right 2010
Sci-Fi Inception 2010
,我需要按流派的電影和串聯類似電影的名字由「」分隔,因此新列表如下像
所需的數據
Genre Name Year
Comedy Shrek Forever After 2010
Drama The Karate Kid, The Kids Are All Right 2010
Action Iron Man 2, Robin Hood 2010
Sci-Fi Inception 2010
的LINQ語句我寫的是如下
Dim result = From p In movies Group p By p.Genre Into Group Select New Movie With {
.Genre = Genre,
.Name = String.Join(", ", Group.Select(Function(p) p.Name).ToArray()),
.Year = Group.Select(Function(p) p.Year).FirstOrDefault
}
有沒有的做,這樣我就不必用另一種方式」 .Year = Group.Select(功能(P)p.Year) .FirstOrDefault「或者與我的方法不同。
感謝
示例代碼:
Module Module1
Sub Main()
Dim movies As New List(Of Movie)
movies.Add(New Movie("Comedy", "Shrek Forever After", 2010))
movies.Add(New Movie("Drama", "The Karate Kid", 2010))
movies.Add(New Movie("Action", "Iron Man 2", 2010))
movies.Add(New Movie("Action", "Robin Hood", 2010))
movies.Add(New Movie("Drama", "The Kids Are All Right", 2010))
movies.Add(New Movie("Sci-Fi", "Inception", 2010))
'Group amd Merge by genre
Dim result = From p In movies Group p By p.Genre Into Group Select New Movie With {
.Genre = Genre,
.Name = String.Join(", ", Group.Select(Function(p) p.Name).ToArray()),
.Year = Group.Select(Function(p) p.Year).FirstOrDefault
}
For Each r In result
Console.WriteLine(r)
Next
Console.ReadKey()
End Sub
Public Class Movie
Public Genre As String
Public Name As String
Public Year As Integer
Public Sub New()
End Sub
Public Sub New(ByVal genre As String, ByVal name As String, ByVal year As Integer)
Me.Year = year
Me.Genre = genre
Me.Name = name
End Sub
Public Overrides Function ToString() As String
Return String.Format("Genre: {0}; Name:{1}; Year:{2}", Genre, Name, Year)
End Function
End Class
End Module
感謝您的回覆,我使用的示例只是爲了得到一個想法,並且我假設每一年都是一樣的,所以您的建議對我有用。上面的LINQ查詢是爲了解決這個問題而優化的。有其他建議嗎? – madan 2011-04-19 16:26:00
@madan我認爲你有適合你的情況。如果按照需要對所有內容進行分組,那麼我認爲不需要改變它,而且查詢很簡單。 – 2011-04-19 16:33:01