Showing posts with label Comma Delimited. Show all posts
Showing posts with label Comma Delimited. Show all posts

Sunday, 16 September 2018

Comma Delimited(Saperated) string of arraylist using LINQ Query

In this post, I will explain how to get Comma Delimited (Separated) string of ArrayList using LINQ Query.

In below example, I want a single string containing all elements from ArrayList with separation character comma(","). 

List<string> str = new List<string>(new string[]{"Harry", "Sandy", "John" , "Mahesh"});

Label1.Text = string.Join(", ", str);

Comma Delimited
ArrayList

Comma Saperated String
Result Comma Separated String

Tuesday, 11 September 2018

Row wise Comma Delimited (Saperated) string using LINQ Query

In this post, I will explain how to get Row wise Comma Delimited (Separated) string using LINQ Query.

In below example, I have two table Department and Employee. Each department having multiple Employees. In result, I want the List of Department with no of employees and a comma-separated list of employees working in that department.

Result Table 

Comma Delimited
LINQ QUERY RESULT TABLE

In the below query, I have used string.Join extension method which returns a comma-separated value for a list of employees.

Syntax - string.Join(",", {array})  

Query to get Row wise Comma Delimited (Saperated) string in LINQ Query :

 var employees = db.Departments.GroupJoin(db.Employees,
                d => d.DepartmentId,
                em => em.DepartmentId,
                (d, em) => new { dept = d, emp = em })
                .Select(d =>
                    new
                    {
                        Department = d.dept.DepartmentName,
                        Count = d.emp.Count(),
                        EmployeeList = string.Join(", ", d.emp
                                          .Select(p => p.EmployeeName).Distinct())
                    });

            GridView1.DataSource = employees;
            GridView1.DataBind();

Department Table 

Comma Delimited
DEPARTMENT TABLE

CREATE TABLE [dbo].[Department](
[DepartmentId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentName] [varchar](100) NULL,
)

Employee Table 

Comma Delimited
EMPLOYEE TABLE

CREATE TABLE [dbo].[Employee](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](100) NULL,
[DepartmentId] [int] NULL,
[Salary] [decimal](18, 2) NULL,
[Age] [int] NULL,
[ZoneId] [int] NULL,
 )