DonMax
DonMax

Reputation: 960

EF GroupBy with concatenate string

I have a table entry something like below,

ColumnA       ColumnB      ColumnC      ColumnD

16             651           a          European Union 
16             651           x          Membership
17             651           a          Great Britain 
17             651           x          Economic integration
18             651           a          European Union countries 
18             651           x          Economic integration

Result List

ColumnA                ColumnB

651                    |a European Union|x Membership
651                    |a European Union countries|x Economic integration
651                    |a Great Britain|x Economic integration 

The idea is to group 3 columns, ie, ColumnA, ColumnB,ColumnC and Concatenate ColumnD.

So far I have done this

var sub = (from x in db.Bs
                   where x.BId == BId
                   group x by new { x.BId, x.Sd, x.TNo, x.Tr } into g
                   select new Book
                   {
                       Tagno = g.Key.TNo,
                       value = " |" + g.Key.Sd + " " + g.Key.   // I am not able to get the Value column here.
                   });

Upvotes: 0

Views: 250

Answers (1)

Jitendra Gupta
Jitendra Gupta

Reputation: 824

Here is complete program for you. The class:

public class TestGroup
{
    public Int16 ColumnA { get; set; }
    public Int16 ColumnB { get; set; }
    public String ColumnC { get; set; }
    public String ColumnD { get; set; }
}

The method:

    public static void GroupTest()
    {
        var testGroup = new List<TestGroup>();
        testGroup.Add(new TestGroup { ColumnA = 16, ColumnB = 651, ColumnC = "a", ColumnD = "European Union" });
        testGroup.Add(new TestGroup { ColumnA = 16, ColumnB = 651, ColumnC = "x", ColumnD = "Membership" });
        testGroup.Add(new TestGroup { ColumnA = 17, ColumnB = 651, ColumnC = "a", ColumnD = "Great Britain" });
        testGroup.Add(new TestGroup { ColumnA = 17, ColumnB = 651, ColumnC = "z", ColumnD = "Economic integration" });
        testGroup.Add(new TestGroup { ColumnA = 18, ColumnB = 651, ColumnC = "a", ColumnD = "European Union countries" });
        testGroup.Add(new TestGroup { ColumnA = 18, ColumnB = 651, ColumnC = "x", ColumnD = "Economic integration" });

        var test = (from x in testGroup
            group x by new {x.ColumnA, x.ColumnB}
            into grp select grp).ToList().Select(grp=> new
            {
                TagNo = grp.Key.ColumnB,
                Text = String.Join(" | ", grp.Select(y => y.ColumnC + " " + y.ColumnD))
            });
        foreach (var x in test)
        {
            Console.WriteLine(String.Format("Tag No: {0}\t Text : {1}", x.TagNo, x.Text));
        }
        Console.Read();
    }

Upvotes: 1

Related Questions