Shpongle
Shpongle

Reputation: 217

Merge LINQ Groups?

Suppose I have these domain objects:

    DataPoint  
    =========  
    public int Id {get;set;}  
    public int TypeId  {get;set;}  
    public string Name  {get;set;}  

    Connector
    =========  
    public DataPoint DataPoint1 {get;set;}  
    public int DataPoint1Id {get;set;}
    public DataPoint DataPoint2 {get;set;}   
    public int DataPoint2Id {get;set;}
    public string Name {get;set;} 
    public int TypeId {get;set;}  

I have a List<Connector>:

    List<Connector> _Connectors = new List<Connector>()
    {
     new Connector(){Name = "a", DataPoint1Id = 1, DataPoint2Id = 2},...
     new Connector(){Name = "b", DataPoint1Id = 1, DataPoint2Id = 2},... 
     new Connector(){Name = "c", DataPoint1Id = 1, DataPoint2Id = 2},...  
     new Connector(){Name = "d", DataPoint1Id = 2, DataPoint2Id = 1},...
     new Connector(){Name = "e", DataPoint1Id = 2, DataPoint2Id = 1}...
    }

I'm doing grouping with LINQ as follows:

    var groups = (from C in _Connectors
                  group C by new { C.DataPoint1Id, C.DataPoint2Id }
                  into cGroup                                             
                  select new {cGroup.Key.DataPoint1Id, cGroup.Key.DataPoint2Id,      
    cGroup.ToList(), cGroup.Count()});

var groups holds:

    DataPoint1Id = 1, DataPoint2Id = 2, list of connectors -"a","b","c", count = 3
    DataPoint1Id = 2, DataPoint2Id = 1, list of connectors - "d","e", count = 2  

I would like to merge these 2 objects into 1 :

    DataPoint1Id = 1, DataPoint2Id = 2, list of connectors - "a","b","c","d","e", count = 5

How can I achieve that?

Upvotes: 0

Views: 563

Answers (1)

Rawling
Rawling

Reputation: 50114

How about

var groups =
    from C in _Connectors
    group C by new
        {
            Min = (int)Math.Min(C.DataPoint1Id, C.DataPoint2Id),
            Max = (int)Math.Max(C.DataPoint1Id, C.DataPoint2Id)
        }
    into cGroup
    select new
        {
            DataPoint1Id = cGroup.Key.Min,
            DataPoint2Id = cGroup.Key.Max,
            Connectors = cGroup.ToList(),
            Count = cGroup.Count()
        };

Upvotes: 1

Related Questions