How to convert a list of arrays to a string divided by a hash?

I am new to C # and I am using String.Join to try turning the list of arrays into a string separated by a hash, like "1 # 2 # 3 # 4". I cannot get the syntax to work correctly.

Here is what I am trying:

ArrayList aryTest = new ArrayList();
aryTest.Add("1");
aryTest.Add("2");
aryTest.Add("3");
string strTest = "";
strTest = string.Join("#", aryTest.ToArray(typeof(string)));
+4
source share
4 answers

What about:

var list = new List<string>() { "1", "2", "3" };
var joined = string.Join("#", list);

An element ArrayListis an “old” generation class that does not implement the IEnumerable<T>interface that is needed for string.Join, and also is not, string[]or an object[]array that can be used in a call string.Join.

List<string>, ToArray, , .

+6

:

strTest = string.Join("#", (string[])aryTest.ToArray(typeof(string)));

ToArray() - :

strTest = string.Join("#", aryTest.ToArray());

, Join:

strTest.ToArray(typeof(string))           ---> string.Join(string, params object[])
    // ToArray(Type) returns Array, it is passed as _one object_,
    // its ToString() is called, the results is "System.String[]"

(string[])strTest.ToArray(typeof(string)) ---> string.Join(string, params string[])

strTest.ToArray()                         ---> string.Join(string, IEnumerable<string>)
    // ToArray() returns object[]
+3

Foreach ,

ArrayList aryTest = new ArrayList();
aryTest.Add("1");
aryTest.Add("2");
aryTest.Add("3");
string strTest = "";
foreach (var a in aryTest)
{
strTest += a +"#";
}
strTest.TrimEnd(new char[] {'#'});
+2

. LINQ , .

 ArrayList aryTest = new ArrayList();
            aryTest.Add("1");
            aryTest.Add("2");
            aryTest.Add("3");
            string strTest = "";            
 strTest = aryTest.ToArray().Aggregate((current, next) => current + "#" + next).ToString();

:

1#2#3

An aggregate is a function that takes a set of values ​​and returns a scalar value. Examples from T-SQL include min, max, and sum. C # supports aggregates and aggregates as extension methods. Using dot notation, you can simply call the method on an IEnumerable object.

Note to keep in mind: since I am not using StringBuilder, it will have negative performance for very long sequences. But for short sequences this will be just fine.

+2
source

Source: https://habr.com/ru/post/1584791/


All Articles