I have a list of data as shown below
Original Data
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
and I need to group the movies by Genre and concatenate similar movies name separated by “,” so the new list looks like
Required Data
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
The LINQ statement I wrote is as follows
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
}
Is there another way of doing it so that I don’t have to use “.Year = Group.Select(Function(p) p.Year).FirstOrDefault” or a different approach than mine.
Thanks
Sample Code:
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
If you’re sure that the
Yearwill never be null, which based on your class it shouldn’t be, you could replace it with this:However, I question your grouping approach. What happens when movies with the same genre don’t share the same year? One might be 2009, another 2010, and you’ll automatically take the first year. You could add an
OrderByto get the most recent year, but it all depends on your grouping intention.