简体   繁体   中英

How to convert a data table data into comma-separated list using lambda expression in C#?

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("SiteName",typeof(string));
dt.Columns.Add(new DataColumn("CountryName",typeof(string));

dt.Rows.Add("ABC","India");
dt.Rows.Add("ABC","China");
dt.Rows.Add("DEF","Japan");
dt.Rows.Add("DEF","Pakistan");
dt.Rows.Add("DEF","Italy");

Required output

    SiteName        CountryName
    ---------------------------------------
    ABC             India,China
    DEF             Japan,Pakistan,Italy
    ---------------------------------------

Please help me to get the above out put using the lambda expression using C#.

Thanks in advance.

Try the following :

DataTable dt=new DataTable();
dt.Columns.Add("SiteName",typeof(string));
dt.Columns.Add("CountryName",typeof(string));

dt.Rows.Add("ABC","India");
dt.Rows.Add("ABC","China");
dt.Rows.Add("DEF","Japan");
dt.Rows.Add("DEF","Pakistan");
dt.Rows.Add("DEF","Italy");

var results = dt.AsEnumerable()
              .GroupBy(x => x.Field<string>("SiteName"))
              .Select(x => new { siteName = x.Key, countries = string.Join(",", x.Select(y => y.Field<string>("CountryName")))})
              .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM