LINQ - Comma Separated - Asked By Barbara M on 08-Dec-11 12:46 PM

hi,

I have one data list contain Grid view. where i have to display the product in COMMA SEPARATED  format in LinQ like: -

laptop, keyboard, mouse, webcam, speaker, headphone

which is store in DB table like;

P_Id   P_Name
-------   ----------
1    
laptop
2    
keyboard
3    
mouse
4    
webcam
5    
speaker
6    
headphone

here i my code:

private void IQuerable GetProduct(int Id, int PId)
 
var Product =
  (from p in Producttable
   where p.Id = Id
   select new
   {
      
 
emails =
  (from r in rows
where r.PId = PId
  group r by r.Name into g
  select new
  {
    P_Id = r.P_Id
    P_Name = r.P_Name
  });
 
return Product;

Please provide the solution and LinQ query to display the products in comma separated....
Suchit shah replied to Barbara M on 08-Dec-11 01:02 PM

See the Below example :
 
var dCounts = 
    (from i in dic 
      group i by i.Value into g 
      select new { g.Key, count = g.Count(), Items = string.Join(",", g.Select(kvp => kvp.Key)) });

The main thing you can achive by :

Use string.Join(",", {array}), passing in your array of keys.

or you may try this option also

string returnVal = (from a in b
select a.StringValue).Aggregate(new StringBuilder(),
(c, d) => c.Append(",").Append(@"""" + d + @""""),
(c) => c.ToString().TrimStart(new char[] { ',' })
.TrimEnd(new char[] { ',' }))

Here "b" is the list and StringValue will be the value which want to get converted to comma separated values.

Riley K replied to Barbara M on 08-Dec-11 07:47 PM


You need not go form that many queries , a simple lambda expression will do,

Assuming your results are of type list

List<MyClass> mc = new List<MyClass>();
      mc.Add(new MyClass { CustId=1, CustName = "John", ProdName = "Pens" });
      mc.Add(new MyClass { CustId = 1, CustName = "John", ProdName = "Shampoo" });
      mc.Add(new MyClass { CustId = 2, CustName = "Kelly", ProdName = "Milk" });
      mc.Add(new MyClass { CustId = 1, CustName = "John", ProdName = "Soap" });
      mc.Add(new MyClass { CustId = 1, CustName = "john", ProdName = "Cadbury" });
      mc.Add(new MyClass { CustId = 2, CustName = "Kelly", ProdName = "Biscuit" });

Now query on the list using Lambda expression

var result = mc.GroupBy(m => m.CustId).Select(gr => new MyClass
   {
     CustName = gr.FirstOrDefault().CustName,
     ProdName =
     string.Join(",", gr.Select(g => g.ProdName).ToArray())
   });
  
   GridView1.DataSource = result;
   GridView1.DataBind();


Regards

Jitendra Faye replied to Barbara M on 09-Dec-11 12:14 AM
Use this code-


private DataTable GetSampleData() {

           
//NOTE: THIS IS JUST FOR DEMO
           
//If you are working with database
           
//You can query your actual data and fill it to the DataTable


           
DataTable dt = new DataTable();
           
DataRow dr = null;

           
//Create DataTable columns
            dt
.Columns.Add(new DataColumn("ID", typeof(string)));
            dt
.Columns.Add(new DataColumn("ProductName", typeof(string)));
            dt
.Columns.Add(new DataColumn("Price", typeof(string)));
            dt
.Columns.Add(new DataColumn("Amount", typeof(string)));


           
//Create Row for each columns
            dr
= dt.NewRow();
            dr
["ID"] = 1;
            dr
["ProductName"] = "Product 1";
            dr
["Price"] = "100";
            dr
["Amount"] = "10";

            dt
.Rows.Add(dr);

            dr
= dt.NewRow();
            dr
["ID"] = 2;
            dr
["ProductName"] = "Product 2";
            dr
["Price"] = "200";
            dr
["Amount"] = "2";

            dt
.Rows.Add(dr);

            dr
= dt.NewRow();
            dr
["ID"] = 3;
            dr
["ProductName"] = "Product 3";
            dr
["Price"] = "50";
            dr
["Amount"] = "10";

            dt
.Rows.Add(dr);

           
return dt;
       
}

       
private DataTable CustomTable(DataTable dtSource) {
           
DataTable dt = new DataTable();
           
DataRow dr;
           
string delCol = string.Empty;

           
if (dtSource.Rows.Count > 0) {
                dt
.Columns.Add(new DataColumn("CommaSeparatedColumn", typeof(string)));

               
foreach (DataRow row in dtSource.Rows) {
                    delCol
+= string.Format("{0},", row["ProductName"]);
               
}

 
                dr
= dt.NewRow();
                dr
["CommaSeparatedColumn"] = delCol.Remove(delCol.Length -1);
                dt
.Rows.Add(dr);

           
}
           
return dt;
       
}


       
protected void Page_Load(object sender, EventArgs e) {
           
if (!IsPostBack) {
               
DataTable source = CustomTable(GetSampleData());
               
GridView1.DataSource = source;
               
GridView1.DataBind();
           
}
       
}




TRy this and let me know.