简体   繁体   中英

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() :

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#.

Let say you have a list of string called listOfString , then you can call the aggregate function like this.

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:

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:

    var commaSeparatedIds = dataTable.ReturnSeparatedString<string>("ID",",");
    var commaSeparatedEAIs = dataTable.ReturnSeparatedString<string>("EAI",",");
    var commaSeparatedInts = dataTable.ReturnSeparatedString<int>("MYINTS",",");
    var dotSeparatedStrings = dataTable.ReturnSeparatedString<int>("OtherId", ".");

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