Mani
Mani

Reputation: 43

Merging two tables and concatenating the values using linq

My table data looks like:

    table 1:
 Id   CId   Message
 1     1    E:MMM
 1     1    E:NNN
 1     1    E:OOO
 1     2    E:PPP 
 1     2    E:PPP

table 2:
 Id   CId   Message
 1     1    W:NNN
 1     1    W:OOO

After merging two tables using linq my output table should be like: Result table:

 Id   CId    ErMessage              WrMessage
 1     1     E:MMM*E:NNN*E:OOO      W:NNN*W.OOO
 1     2     E:PPP*E:PPP 

Please help me how to achieve.

Upvotes: 1

Views: 284

Answers (1)

Michael Samteladze
Michael Samteladze

Reputation: 1330

 var q =
    from t1 in
        table1.GroupBy(g => g.ID).Select(g => new
        {
            ID = g.Key,
            Message = string.Join("*", g.Select(v => v.Message).ToArray())
        })
    join
        t2 in
        table2.GroupBy(g => g.ID).Select(g => new
        {
            ID = g.Key,
            Message = string.Join("*", g.Select(v => v.Message).ToArray())
        }) on t1.ID equals t2.ID
    select new
    {
        ID = t1.ID,
        ErMessage = t1.Message,
        WrMessage = t2.Message
    };

Upvotes: 3

Related Questions