How to Use Array.Exists with the Multi-dimensional string array - c#

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));

Related

How to delete element from array?

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.

Nested For loop multidimensional array search

Got a silly question im struggling with.
Im trying to step through a C# Multidimensional array using nested for loops, but i cant get the result i want and im thinking its just a stupid problem with my code.
string search = txtString.Text;
int iLoop;
int jloop;
int iResult = -1;
for (iLoop = 0; iLoop < sounds.GetLength(0) ; iLoop++)
{
for (jloop = 0; jloop < sounds.GetLength(1) ; jloop++)
{
string result;
result = sounds[iLoop,jloop];
if (result == search)
{
iResult = iloop;
}
}
}
if (iResult == -1)
{
MessageBox.Show("Result not found");
}
else
{
MessageBox.Show("Result found at position " + iResult);
}
}
It searches the array, and returns a positive result if the answer is found, but the result position is always "Result found at position 1".
What have i done wrong?
You are storing only one dimension (iResult). It can always be 1, but second dimension (jresult) can vary.
And just reminder for future projects in different languages. Try no to use if (result == search) for strings. Use Equal or Compare methods.
There are two indices to look up: jloop and iLoop , probably you will get various jloop values in the 2D array
Also check the name on the parameter you use, sometimes you call it iLoop, others iloop.
Be consistent! :)
I guess the answer is always in row 1, you just pring the i value, print also the j value jLoop.
Keep in mind that this code snippet will continue searching even after it has found a match. So in fact what you are finding is the last position of the matched text.
As an aside, perhaps instead of reporting only the matching iLoop, you could report both the matching iLoop and jLoop. Or, you can report a single index as iLoop * sounds.GetLength(0) + jLoop

Find intersection of two multi-dimensional Arrays in C# 4.0

Trying to find a solution to my ranking problem.
Basically I have two multi-dimensional double[,] arrays. Both containing rankings for certain scenarios, so [rank number, scenario number]. More than one scenario can have the same rank.
I want to generate a third multi-dimensional array, taking the intersections of the previous two multi-dimensional arrays to provide a joint ranking.
Does anyone have an idea how I can do this in C#?
Many thanks for any advice or help you can provide!
Edit:
Thank you for all the responses, sorry I should have included an example.
Here it is:
Array One:
[{0,4},{1,0},{1,2},{2,1},{3,5},{4,3}]
Array Two:
[{0,1},{0,4},{1,0},{1,2},{3,5},{4,3}]
Required Result:
[{0,4},{1,0},{1,2},{1,1},{2,5},{3,3}]
Here's some sample code that makes a bunch of assumptions but might be something like what you are looking for. I've added a few comments as well:
static double[,] Intersect(double[,] a1, double[,] a2)
{
// Assumptions:
// a1 and a2 are two-dimensional arrays of the same size
// An element in the array matches if and only if its value is found in the same location in both arrays
// result will contain not-a-number (NaN) for non-matches
double[,] result = new double[a1.GetLength(0), a1.GetLength(1)];
for (int i = 0; i < a1.GetLength(0); i++)
{
for (int j = 0; j < a1.GetLength(1); j++)
{
if (a1[i, j] == a2[i, j])
{
result[i, j] = a1[i, j];
}
else
{
result[i, j] = double.NaN;
}
}
}
return result;
}
For the most part, finding the intersection of multiple dimensional arrays will involve iterating over the elements in each of the dimensions in the arrays. If the indices of the array are not part of the match criteria (my second assumption in my code is removed), you would have to walk each dimension in each array - which increases the run-time of the algorithm (in this case, from O(n^2) to O(n^4).
If you care enough about run-time, I believe array matching is one of the typical examples of dynamic programming (DP) optimization; which you can read up on at your leisure.
I'm not sure how you wanted your results...you could probably return a flat collection of results that can be indexed by a pair, which would potentially save a lot of space if the expected result set is typically small. I went with a third fixed-sized array because it was the easiest thing to do.
Lastly, I'll mention that I don't see a keen C# way of doing this using IEnumerable, LINQ, or something like that. Someone more C# knowledgeable than I can chime in anytime now....
Given the additional information, I'd argue that you aren't actually working with multidimensional arrays, but instead are working with a collection of pairs. The pair is a pair of doubles. I think the following should work nicely:
public class Pair : IEquatable<Pair>
{
public double Rank;
public double Scenario;
public bool Equals(Pair p)
{
return Rank == p.Rank && Scenario == p.Scenario;
}
public override int GetHashCode()
{
int hashRank= Rank.GetHashCode();
int hashScenario = Scenario.GetHashCode();
return hashRank ^ hashScenario;
}
}
You can then use the Intersect operator on IEnumerable:
List<Pair> one = new List<Pair>();
List<Pair> two = new List<Pair>();
// ... populate the lists
List<Pair> result = one.Intersect(two).ToList();
Check out the following msdn article on Enumerable.Intersect() for more information:
http://msdn.microsoft.com/en-us/library/bb910215%28v=vs.90%29.aspx

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

Loop through comma delimited string, split into multiple arrays?

I have a string coming in the format:
div, v6571, 0, div, v8173, 300, p, v1832, 400
I want to split this string into multiple arrays, for the example above I would need 3 arrays, such that the format would be like this:
item[0] -> div
item[1] -> v6571
item[2] -> 0
I know that I can just do a .Split(',') on the string and put it into an array, but that's one big array. For the string example above I would need 3 arrays with the structure provided above. Just getting a bit confused on the iteration over the string!
Thanks!
I'm not sure exactly what you're looking for, but to turn the above into three separate arrays, I'd do something like:
var primeArray = yourString.Split(,);
List<string[]> arrays = new List<string[]>();
for(int i = 0; i < primeArray.Length; i += 3)
{
var first = primeArray[i];
var second = primeArray[i+1];
var third = primeArray[i+2];
arrays.Add(new string[] {first, second, third});
}
Then you can iterate through your list of string arrays and do whatever.
This does assume that all of your string arrays will always be three strings long- if not, you'll need to do a foreach on that primeArray and marshal your arrays more manually.
Here's the exact code I used. Note that it doesn't really change anything from my original non-compiled version:
var stringToSplit = "div, v6571, 0, div, v8173, 300, p, v1832, 400";
List<string[]> arrays = new List<string[]>();
var primeArray = stringToSplit.Split(',');
for (int i = 0; i < primeArray.Length; i += 3)
{
var first = primeArray[i];
var second = primeArray[i + 1];
var third = primeArray[i + 2];
arrays.Add(new string[] { first, second, third });
}
When I check this in debug, it does have all three expected arrays.
.Split(",") is your best bet. You can then modify that string array to reflect whatever structure you need.
You could use Regular Expressions or other methods, but nothing will have the performance of String.Split for this usage case.
The following assumes that your array's length is a multiple of three:
var values = str.Split(',')
string[,] result = new string[values .Length / 3, 3];
for(int i = 0; i < params.Length; i += 3)
{
int rowIndex = i / 3;
result[rowIndex, 0] = values [i];
result[rowIndex, 1] = values [i + 1];
result[rowIndex, 2] = values [i + 2];
}
Compiled in my head, but it should work.
Just so that I'm understanding you right, you need to sort them into:
1) character only array
2) character and number
3) numbers only
If so, you can do the following:
1) First try to parse the string with Int32.Parse
if successful store in the numbers array
2) Catch the exception and do a regex for the numbers
to sort into the remainder 2 arrays
Hope it helps (: Cheers!

Categories

Resources