Using array.ElementAt(0); we can get the element at index 0 of the array. Is there a method to get all the elements 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.
Related
Trying to find the more efficient way to check if a string contains words(strings) from an array.
I have a list of strings. When I'm looping through them, I want to check if the current string has some specific words in it. For storing those words I use an array of strings. So, I was wondering if there was a way with linq?(or just more efficient way) Something like string.Any() for strings?
I did it with loops, but I don't personally like it:
First of all, the main list and array:
List<string> lista = new List<string>() {"\r\n", "<p>This is a paragrath</p>", "<h2>This is a subheader</h2>", "\r\n" };
string[] arr = new string[] {"<h1>","<h2>","<h3>","<p>" };
Now I go into the loops:
for(int i = 0; i < lista.Count; i++)
{
if(lista[i] != "\r\n")
for(int j = 0; j < arr.Length; j++)
{
if(lista[i].Contains(arr[j]))
{
...
}
}
}
As I've said above, I don't like it this way. Is there any other method?
This will give you all items in lista which at least contains one element of arr:
string[] result = lista.Where(x => arr.Any(a => x.Contains(a)).ToArray()
Written in linq syntax I think it's a bit more readable.
var allThatContainTags = from html in lista
where html != "\r\n" && arr.Any(html.Contains)
select html;
I have an string array like this
K={"book","handbook","car"}
I would like to check if any string contains other string,if it does I would like to remove it from array .In the case of array K,new array should be like this
K="{"book","car"}
for (i = 0; i < 10; i++)
{
if (keywords.Contains(keywords[i])) {
//I have no idea for this part
}
}
It might make more sense to use a List<>, a data structure designed for editing, whereas an array is a fixed structure. But, assuming you have an array, and need to end up with a modified array, you could convert:
IEnumerable<string> invalid_words = // ... list of words K cannot contain
string[] K = // .. array of strings you are given
K = K.Where(p => !invalid_words.Contains(p)).ToArray();
This might be a little "smelly" but it's better than try to modify the array when you are in an iteration.
The idea is this: save all the indexes where the word appears, and then erase those words. This is not the best solution, but it can help you with your problem. I highly recommends you to read about "Lists" because there are great on C# and it's easier use them than use arrays
K="{"book","car"};
//Never use a number, try to use the .length propertie
List<int> indexes=new List<int>();//using lists is easier than arrays
enter code here
for (i = 0; i < K.length; i++)
{
if (keywords.Contains(K[i]))
{
//You save the index where the word is
indexes.add(i);
}
}
//Here you take those indexes and create a new Array
int[] theNewArray=new int[K.length-indexes.Count];
int positionInTheNewArray=0;
for (i = 0; i < K.length; i++)
{
if(!indexes.Contains(i))
{ theNewArray[positionInTheNewArray]=K[i];
positionInTheNewArray++;
}
}
}
That fits if your array allows duplicated words and also if duplicated words are not allowed.
I would like to add a column of zeros to all of my double[] in my List<List<double[]>>().
The length of the double[] is currently 2 and I would like to have doubles[] of length 3. The zero should always be in the third position, for example:
double[50, 75] // double [50,75,0]
This has to be done in all of the List<double[]> within List<List<double[]>>.
Is there a short way to do this?
There is a short way of doing this in terms of lines of code, but the number of allocations and copying is equal to the number of arrays in the original list:
var res = orig.
Select(list => list
.Select(array => array.Concat(new[] {0.0}).ToArray())
.ToList()
).ToList();
Demo.
because you want to extend the array in the source list you need to manipulate them in the internal list:
foreach (var list in rootList)
{
for (var i = 0; i < list.Count; i++)
{
var actor = list[i];
list[i] = new double[actor.Length + 1]; // all elements will be 0....
Array.Copy(list[i], actor, actor.Length); //just add the prev elements
}
}
the above operation will apply the change on all pointers to List<List<double[]>>.
if you don't want to make the change on all pointer to rootList, #dasblinkenlight answer is good enough.
I have a multi-dim string array something like this:-
string[,] names = new string[2, 2] { {"Rosy",""}, {"Peter","Albert"} };
Now i want to check the existence if the second index (Albert) holding the string is non-empty in the whole array. I just to check the existence of the non-empty string value in the second index.
I was thinking of using the Array.Exists. If there is any other better way, please share.
Thanks
I don't think you can use Array.Exists here, because that only deals with the values - you're interested in the position too. I would just use a loop:
bool found = false;
for (int i = 0; i < names.GetLength(0); i++)
{
if (!string.IsNullOrEmpty(names[i, 1]))
{
found = true;
break;
}
}
Rectangular arrays are basically a bit of a pain to work with in C#. If you had a jagged array - an array of arrays - it would be easy:
bool found = jagged.Select(x => x[1])
.Any(value => !string.IsNullOrEmpty(value));
I have a scenario where I have a list of classes, and I want to mix up the order. For example:
private List<Question> myQuestions = new List<Question>();
So, given that this is now populated with a set of data, I want to mix up the order. My first thought was to create a collection of integers numbered from 1 to myQuestions.Count, assign one at random to each question and then loop through them in order; however, I can’t seem to find a suitable collection type to use for this. An example of what I mean would be something like this:
for (int i = 0; i <= myQuestions.Count -1; i++)
tempCollection[i] = myQuestions[rnd.Next(myQuestions.Count-1)];
But I’m not sure what tempCollection should be – it just needs to be a single value that I can remove as I use it. Does anyone have any suggestions as to which type to use, or of a better way to do this?
I suggest you copy the results into a new List<Question> and then shuffle that list.
However, I would use a Fisher-Yates shuffle rather than the one you've given here. There are plenty of C# examples of that on this site.
For example, you might do:
// Don't create a new instance of Random each time. That's a detail
// for another question though.
Random rng = GetAppropriateRandomInstanceForThread();
List<Question> shuffled = new List<Question>(myQuestions);
for (int i = shuffled.Count - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
Question tmp = shuffled[i];
shuffled[i] = shuffled[swapIndex];
shuffled[swapIndex] = tmp;
}
You could use Linq and order by a random value:
List<string> items = new List<string>();
items.Add("Foo");
items.Add("Bar");
items.Add("Baz");
foreach (string item in items.OrderBy(c => Guid.NewGuid()))
{
Console.WriteLine(item);
}
temp Collection should be same type as myQuestions.
I would also suggest a change in your code:
for (int i = 0; i <= myQuestions.Count -1; i++)
to
for (int i = 0; i < myQuestions.Count; i++)
Does the same thing, but this is how most programers do it so it will make your code simpler to read.