如何对匿名类型的集合进行排序

时间:2016-05-22 14:11:33

标签: c# linq

使用Linq to SQL我从数据库匿名集合中获取。集合如下所示:

1. { PS_DID = 523, ID = 2, TITLE = "Station1", ACTIVE = 1, status = null, validFrom = null }
2. { PS_DID = 402, ID = 4, TITLE = "Station2", ACTIVE = 1, status = null, validFrom = null }
3. { PS_DID = 8, ID = 152, TITLE = "Station3", ACTIVE = 1, status = 5, validFrom = {5/26/2015 12:00:01 AM} }    
4. { PS_DID = 8, ID = 152, TITLE = "Station3", ACTIVE = 1, status = 5, validFrom = {5/26/2015 12:00:01 AM} }
5. { PS_DID = 13, ID = 75, TITLE = "Station4", ACTIVE = 1, status = 5, validFrom = {1/12/2016 12:00:01 AM} }
6. { PS_DID = 13, ID = 75, TITLE = "Station4", ACTIVE = 1, status = 5, validFrom = {12/1/2015 12:00:01 AM} }
7. { PS_DID = 13, ID = 75, TITLE = "Station4", ACTIVE = 1, status = 3, validFrom = {3/20/2016 12:00:01 AM} }
8. { PS_DID = 13, ID = 75, TITLE = "Station4", ACTIVE = 1, status = 1, validFrom = {5/19/2016 11:07:00 PM} }
9. { PS_DID = 13, ID = 75, TITLE = "Station4", ACTIVE = 1, status = 1, validFrom = {5/20/2016 3:50:00 PM} }

我想按照车站的ID订购匿名收集,其中每个车站将包含不同状态的列表,每个状态将包括不同日期的列表。
新的集合应如下所示:

1.  PS_DID = 523, ID = 2, TITLE = "Station1", ACTIVE = 1, status = null, validFrom = null 
2.  PS_DID = 402, ID = 4, TITLE = "Station2", ACTIVE = 1, status = null, validFrom = null 
3.  PS_DID = 8, ID = 152, TITLE = "Station3", ACTIVE = 1, 
 - status 
    * 5 - (validFrom = 5/26/2015 12:00:01 AM) 
4.  PS_DID = 13, ID = 75, TITLE = "Station4", ACTIVE = 1
 - status 
    * 5 - validFrom 
       * 1/12/2016 12:00:01 AM
       * 2/1/2015 12:00:01 AM
    * 3 - validFrom 
       * 3/20/2016 12:00:01 AM
    * 1 - validFrom
       * 5/19/2016 11:07:00 PM
       * 5/20/2016 3:50:00 PM

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您需要的是分组,您可以使用Linq

您必须将输入集合分组两次,一次放在ID字段上,然后放在status字段上。

var results= collection.GroupBy(g=> new {g.PS_DID,  g.ID , g.TITLE,  g.ACTIVE})
          .OrderBy(x=>x.Key.PS_DID)
          .Select(x=> new 
           {
                PS_DID = g.Key.PS_DID,
                ID = g.Key.ID,
                TITLE = g.Key.TITLE,
                ACTIVE = g.Key.ACTIVE,
                STATUS_VALID_DATE = x.GroupBy(g=> g.status)
                                     .Select(s=> new {
                                          status = s.Key, 
                                          validFrom = s.Select(v=>v.validrom).ToList() 
                                     }).ToList()
           });