0

我有一个清单:

var list = new List<Test>{
   new Test = {
        ID = 1,
        Name = "Test 1",
        RefId = 1
        RefName = "Test RefName 1"
   },
   new Test = {
        ID = 2,
        Name = "Test 2",
        RefId = 1
        RefName = "Test RefName 1"
   },
   new Test = {
        ID = 3,
        Name = "Test 3",
        RefId = 2
        RefName = "Test RefName 2"
   },
   new Test = {
        ID = 4,
        Name = "Test 4",
        RefId = 2
        RefName = "Test RefName 2"
   }
};

我想将顶部列表转换为新列表:

var list = new List<TestNew>{
    new TestNew = {
       RefId = 1,
       RefName = "Test RefName 1",
       ListGroup = new List<Group>{
          new Group{
             ID = 1,
             Name = "Test 1"
          },
          new Group{
             ID = 2,
             Name = "Test 2"
          },
       }
    },
   new TestNew = {
       RefId = 2,
       RefName = "Test RefName 2",
       ListGroup = new List<Group>{
          new Group{
             ID = 3,
             Name = "Test 3"
          },
          new Group{
             ID = 4,
             Name = "Test 4"
          },
       }
    }
};
4

2 回答 2

2
list.GroupBy(x => new { x.RefId, x.RefName })
    .Select(g => new TestNew() {
        RefId = g.Key.RefId,
        RefName = g.Key.RefName,
        ListGroup = g.Select(y => new Group() {
            ID = y.ID,
            Name = y.Name
        }).ToList()
    }).ToList();
于 2013-07-23T06:55:11.140 回答
1

这样的事情应该可以解决问题:

list.GroupBy(item => item.RefId)
    .Select(grouping => new ListNew() {
           RefId = grouping.Key,
           RefName = grouping.First().RefName,
           ListGroup = grouping.Select(i => new Group() { ID = i.ID, Name = i.Name }).ToList()
     })
     .ToList();

这确实假设 RefName/RefId 始终是一致的。

于 2013-07-23T06:59:02.373 回答