开发者

C# get all elements of array

Using array.ElementAt(0); we can get the element at index 0 of the array. Is there a method to get all the el开发者_如何学Pythonements in an array?

string[] arr1 = {'abc', 'def', 'ghi'}
Library.Results["TEST_ACTUALVALUE"] = "The results are: " + arr1;

TEST_ACTUALVALUE is a column in my report.xls file. The above writes System.string[] in my excel file.


You already have all of the elements in the array...the array itself.

The simple answer is iterate over them:

foreach(var item in array)
{
    // work with item here
}

Or if you'd rather deal with indexes:

for(var i = 0; i < array.Length; i++)
{
    var item = array[i];
    // work with item here
}


It's hard to know what you mean by "get all the elements in an array" because you already have all the elements....in the array.

If you mean concatinating a string from a string array then something like:

var concatinatedString = String.Concat(myArrayOfStrings);


There's a hundred ways to skin that cat. Largely it should depend on what you wish to do with all the elements. Heres the old school for loop method:

for(int i = 0; i < array.Length; i++)
{
    something = array[i];
}


I'm not sure why you'd do this, but there is a array.All available. Try that?


Depending on what you want to get the elements for there are many methods you can look into

Get all the elements in an array

for(int x = 0; x < array.Length; x++)
{
    something = array[x];
    somethingElse = array.ElementAt(x);
} 

Make an array a list to get all values:

List<T> myList = array.ToList<T>();

From here you can do all list methods with that array to get all values.

If you are trying to take the sum of every element use:

sum = array.Sum();

To get the max/min value in the array:

max = array.Max();
min = array.Min();

To get the average:

double average = array.Average(num => Convert.ToInt64(num));

There are many other ways to get all information from an array, here


The question is how to join a string array together. Solution:

... = "The results are: " + String.Join (", ", arr1);

And a note: you don't have to and should not use array.ElementAt(0) to get an element. Use array[0].


Going to go out on a limb here and recommend using a loop?


Why are you using ElementAt? You can just use the indexer:

var value = array[0];

In general:

var ithValue = array[i];


The Array class implements the IList, ICollection, and IEnumerable interfaces. So you can use any needed method of these interfaces.

Eventually, you can write foreach loop to traverse through array.


//IF the array type is string, you can follow below:
//else you need to convert to string 1st.

String Result = "";

For (int i=0; i<array.length; i++)
{
 Result = Result + array[i];
}

// The result will consist all the array element.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜