[英]Split list values into comma separated strings
I am picking distinct values from a datatable column like below. 我从像下面的数据表列中选择不同的值。
var uniqueCC = dtNew.AsEnumerable().Select(s => new { cc = s.Field<string>("ID"), }).Distinct().ToList();
var uniqueCode = dtNew.AsEnumerable().Select(s => new { Code = s.Field<string>("EAI"), }).Distinct().ToList();
Now I need to get the values alone in a comma seperated string and I'm using the below code and it doesn't take the value alone. 现在我需要在逗号分隔的字符串中单独获取值,并且我使用下面的代码并且它不单独使用值。
string strCC = String.Join(",", uniqueCC);
string strEAI = String.Join(",", uniqueCode);
Please provide some suggestions. 请提供一些建议。
List values 列出值
cc=1, cc=2, cc=3
Expected Result 预期结果
1,2,3
You can just use LINQ Select()
method to pass the value alone to String.Join()
: 您可以使用LINQ
Select()
方法将值单独传递给String.Join()
:
string strCC = String.Join(",", uniqueCC.Select(o => o.cc));
Or just return string values instead of anonymous type in the first place : 或者只是首先返回字符串值而不是匿名类型:
var uniqueCC = dtNew.AsEnumerable().Select(s => s.Field<string>("ID")).Distinct();
string strCC = String.Join(",", uniqueCC);
You can use aggregate
functions available in c#. 您可以使用c#中提供的
aggregate
函数。
Let say you have a list of string called listOfString
, then you can call the aggregate function like this. 假设您有一个名为
listOfString
的字符串列表,那么您可以像这样调用聚合函数。
string outString = listOfString.Aggregate((a, b) => a + "," + b);
It will do the trick. 它会做到这一点。
As an extension to har07's excellent answer, if this is something you do a lot of the time, to save writing loads of code you could implement this as a static extension method, where you pass the datatype, the column name and your required separator - so it could handle different column datatypes and separators - in a separate file: 作为har07优秀答案的扩展,如果这是您经常做的事情,为了节省编写代码的负载,您可以将其实现为静态扩展方法,您可以在其中传递数据类型,列名称和所需的分隔符 - 所以它可以处理不同的列数据类型和分隔符 - 在一个单独的文件中:
namespace Extensions
{
public static class LinqExtensions
{
public static String ReturnSeparatedString<T>(this DataTable datatable, string field, string separator)
{
var unique =
datatable.AsEnumerable()
.Select(s => new {cc = s.Field<string>(field),}).Distinct();
return String.Join(separator, unique.Select(o => o.cc));
}
}
}
Then call it from your code by creating a reference to your new Extensions.LinqExtensions class, and calling it directly on the dataTable like this: 然后通过创建对新Extensions.LinqExtensions类的引用从代码中调用它,并直接在dataTable上调用它,如下所示:
var commaSeparatedIds = dataTable.ReturnSeparatedString<string>("ID",",");
var commaSeparatedEAIs = dataTable.ReturnSeparatedString<string>("EAI",",");
var commaSeparatedInts = dataTable.ReturnSeparatedString<int>("MYINTS",",");
var dotSeparatedStrings = dataTable.ReturnSeparatedString<int>("OtherId", ".");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.