[英]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#.请帮助我使用 C# 使用 lambda 表达式获得上述结果。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.