2011-04-19 44 views
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 

回答

2

如果你确保Year永远不会为空,这基于你的类不应该是,你可以取代它与此:

.Year = Group.First().Year 

但是,我质疑你的分组方法。当具有相同类型的电影不共享同一年时会发生什么?一个可能是2009年,另一个2010年,你会自动拿到第一年。您可以添加OrderBy以获取最近的一年,但这一切都取决于您的分组意图。

+0

感谢您的回复,我使用的示例只是为了得到一个想法,并且我假设每一年都是一样的,所以您的建议对我有用。上面的LINQ查询是为了解决这个问题而优化的。有其他建议吗? – madan 2011-04-19 16:26:00

+0

@madan我认为你有适合你的情况。如果按照需要对所有内容进行分组,那么我认为不需要改变它,而且查询很简单。 – 2011-04-19 16:33:01