如何使用在Linq中包含相同id的元素从现有列表创建新列表?

时间:2013-07-23 06:50:09

标签: c# linq list tree converter

我有一个清单:

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"
          },
       }
    }
};

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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始终是一致的。