I am currently trying to use a string array populated with values from Class B in Class A.
I have tried to copy the array over as such
string[] playerHand2 = new string[5];
Array.Copy(Deck.playerHand, playerHand2, 5);
However I get a null reference exception when I try to display the contents like so:
Console.WriteLine("Players hand:");
foreach (var item in playerHand2)
{
Console.Write(item.ToString());
}
Any adive pointing me in the correct direction is much appreciated.
One of the items in Deck.playerHand was already null.
This null value is copied into playerHand2.
When itterating through playerHand2, null.ToString() is called, resulting in your NullReferenceException.
You can check for a null-value with:
bool hasNulls = Array.IndexOf(Deck.playerHand, null) > 0;
or with LINQ:
bool hasNulls = Deck.playerHand.Any(s => s == null);
You do not need to copy the Array to use it, and converting a string to string is not helpful.
You can simply use:
foreach (var item in Deck.playerHand)
{
Console.WriteLine(item);
}
in general, you can also overwrite null with " " using the following:
for(int x = 0; x < Deck.playerHand.Length; x++)
{
if(Deck.playerHand[x] == null)
{
Deck.playerHand[x] = " ";
}
}
combined that gives following code:
for(int x = 0; x < Deck.playerHand.Length; x++)
{
if(Deck.playerHand[x] == null)
{
Deck.playerHand[x] = " ";
}
Console.WriteLine(Deck.playerHand[x]);
}
or even more compact, see #saravanan:
foreach(string item in Deck.playerHand)
{
Console.Write(!string.IsNullOrEmpty(item)?item.ToString():"");
}
The following code works perfectly fine for me:
string[] playerHand = new string[7] { "1", "2", "3", "4", "5", "6", "7" };
string[] playerHand2 = new string[5];
Array.Copy(playerHand, playerHand2, 5);
Console.WriteLine("Players hand:");
foreach (var item in playerHand2)
{
Console.Write(item.ToString());
}
Did you actually fill your array 'playerHand' with valid data?
Else make sure you have no null-values in the array of 'playerHand', and the size of 'playerHand' must be at least as big as 'playerHand2'.
Else you can simply avoid this
foreach (var item in playerHand2)
{
if (string.IsNullOrEmpty(item)) { continue; }
Console.Write(item.ToString());
}
Related
I have a json array that looks like...
{
"equipment": [{
"date_of_examination": "2022-05-20T14:08:38.072965",
"defect_type": ["DN"],
"eqpt_ref": "AA1",
"eqpt_name": ["2 Leg Chain Sling"],
"eqpt_manufacturer": "Merc",
"eqpt_model": "edes",
"part_no": "A1",
"serial_no": "A1",
"year": "2019",
"swl": "32 tons",
"exam_type": ["6 Months"],
"date_of_last_examination": "2021-11-20T00:00:00",
"date_of_next_examination": "2022-11-20T00:00:00",
"defect": "sling is torn",
"action_required": "replace"
}, {
"date_of_examination": "2022-05-20T14:12:23.997004",
"eqpt_ref": "AA2",
"eqpt_name": ["Other - "],
"eqpt_name_other": "widget",
"eqpt_manufacturer": "merc",
"eqpt_model": "edes",
"part_no": "B1",
"serial_no": "B1",
"year": "2019",
"swl": "32 tons",
"exam_type": ["6 Months"]
}, {
"date_of_examination": "2022-05-20T14:13:24.795136",
"defect_type": ["DF"],
"eqpt_ref": "CC1",
"eqpt_name": ["Endless Round Sling (2.5m)"],
"eqpt_manufacturer": "merc",
"eqpt_model": "edes",
"part_no": "c1",
"serial_no": "c1",
"year": "2019",
"swl": "42 tons",
"exam_type": ["6 Months"],
"defect": "stitching is coming undone",
"danger_value": "6",
"danger_units": ["Weeks"],
"action_required": "needs to be stitched again"
}]
}
I am attempting to loop through the array and filter items as I need, to populate a table later.
The table has three parts.
First, is show all items with a defect_type of "DN". Second is to show all defect_type of "DF", and the last part is to show all the rest (in his case, the one with eqpt_name of AA2)
My original code is...
for (int j = 0; j <= 2; j++)
{
// Note, some table name parts won't have the "Filter..." aspect
// the string below will change depending on which loop we are in.
string[] tableNameParts = "TableStart:equipment:defectNow:Filter:defect_type=DN".Split(':');
string tableNameJson = tableNameParts[1].Replace("»", "");
var jsonRows = IncomingJson[tableNameJson];
if (tableNameParts.Count() > 3)
{
// We probably have a filter set.
if (tableNameParts[3].Replace("»", "").ToLower() == "filter" && tableNameParts.Count() > 4)
{
// These values are not set in stone. It is what values have been set in the JSON, and then matched.
// for example... TableStart:<subform name>:<differentiator>:Filter:<field name>=<field value>
string[] FilterParts = tableNameParts[4].Split('=');
// Get the filter field and value to filter by
if (FilterParts.Count() > 1)
{
string FilterField = FilterParts[0].Replace("»", "");
string FilterValue = FilterParts[1].Replace("»", "");
JArray filteredArray = new JArray();
if (jsonRows[0].GetType() == typeof(JObject))
{
//int loopCount = 0;
foreach (JObject arrayObject in jsonRows) // Each group can have a set of arrays. (each record has multiple sub records)
//for (int i = 0; i < jsonRows.Count(); i++)
{
//JObject arrayObject = jsonRows[i];
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
//loopCount++;
}
}
else
{
foreach (JArray arrayGroup in jsonRows) // The array group (e.g. fault_record_subform)
{
// We are looking through the json array, to find any rows that match our filter key and filter value.
// We will then add that into our jsonRows
//int loopCount = 0;
foreach (JObject arrayObject in arrayGroup) // Each group can have a set of arrays. (each record has multiple sub records)
{
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
}
//loopCount++;
}
}
//filteredArray.CopyTo(testArray, 0);
jsonRows = filteredArray; // limit the jsonRows to the filtered set (overwrite the jsonRows)
}
}
}
else
{
// This is not a filter set
JArray singleArray = new JArray();
foreach(var arraySet in jsonRows)
{
if (!testArray.Intersect(arraySet).Any())
{
if (arraySet.GetType() == typeof(JObject))
{
singleArray.Add(arraySet);
}
else
{
foreach (JObject arrayObject in arraySet)
{
singleArray.Add(arrayObject);
}
}
}
}
jsonRows = singleArray;
}
}
By the time it gets to the "this is not a filter set" (which should be the third iteration of the loop), I need to be able to ignore the other filtered items, but as you might see, I have attempted to mark an item as filtered (then filter out). I have also tried to add the filtered items to an alternative array and use that to filter out. All to no avail.
How do I make it so that the "this is not a filter set" rows can ignore the rows already filtered?
=========== EDIT ==============
After reviewing the link from dbc to the fiddler (I don't have an account on there, and don't know how to link to my changes), I have it running in the fiddler with the code below.
JObject json = JObject.Parse(GetJson());
string[] tableNames = {"TableStart:equipment:defectNow:Filter:defect_type=DN","TableStart:equipment:defectFuture:Filter:defect_type=DF","TableStart:equipment:defectNone"};
for (int j = 0; j <= 2; j++)
{
// Note, some table name parts won't have the "Filter..." aspect
// the string below will change depending on which loop we are in.
string[] tableNameParts = tableNames[j].Split(':');
string tableNameJson = tableNameParts[1].Replace("»", "");
var jsonRows = json[tableNameJson];
if (tableNameParts.Count() > 3)
{
// We probably have a filter set.
if (tableNameParts[3].Replace("»", "").ToLower() == "filter" && tableNameParts.Count() > 4)
{
// These values are not set in stone. It is what values have been set in the JSON, and then matched.
// for example... TableStart:<subform name>:<differentiator>:Filter:<field name>=<field value>
string[] FilterParts = tableNameParts[4].Split('=');
// Get the filter field and value to filter by
if (FilterParts.Count() > 1)
{
string FilterField = FilterParts[0].Replace("»", "");
string FilterValue = FilterParts[1].Replace("»", "");
JArray filteredArray = new JArray();
if (jsonRows[0].GetType() == typeof(JObject))
{
//int loopCount = 0;
foreach (JObject arrayObject in jsonRows) // Each group can have a set of arrays. (each record has multiple sub records)
//for (int i = 0; i < jsonRows.Count(); i++)
{
//JObject arrayObject = jsonRows[i];
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
//testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
//loopCount++;
}
}
else
{
foreach (JArray arrayGroup in jsonRows) // The array group (e.g. fault_record_subform)
{
// We are looking through the json array, to find any rows that match our filter key and filter value.
// We will then add that into our jsonRows
//int loopCount = 0;
foreach (JObject arrayObject in arrayGroup) // Each group can have a set of arrays. (each record has multiple sub records)
{
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
//testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
}
//loopCount++;
}
}
//filteredArray.CopyTo(testArray, 0);
jsonRows = filteredArray; // limit the jsonRows to the filtered set (overwrite the jsonRows)
}
}
}
else
{
// This is not a filter set
JArray singleArray = new JArray();
foreach(var arraySet in jsonRows)
{
//if (!testArray.Intersect(arraySet).Any())
{
if (arraySet.GetType() == typeof(JObject))
{
singleArray.Add(arraySet);
}
else
{
foreach (JObject arrayObject in arraySet)
{
singleArray.Add(arrayObject);
}
}
}
}
jsonRows = singleArray;
}
}
What I need ultimately (the jsonRows will be used elsewhere in my code within the loop) is that the third set will have items not found in the first 2 sets.
After a bit of further experimentation, using dotnetfiddle as introduced to me by #dbc (thank you), I have created a List and added each arrayObject into the list during the filtering stages.
I then during the unfiltered stage check if my arraySet is contained in the List, and if not, then add that item to the remaining jsonRows, thereby giving me the balance of the original list.
As can be seen here...
https://dotnetfiddle.net/ot35Z2
I have an array of string, I want to take all the string in an interval of this array until string does not contains something.
Something like:
string [] arrayReading = {
"e","x","a","takefromhere",
"keeptaking","keeptaking","dont'ttakefromhere","m","p","l","e"
};
I have tried:
List<string> result = null;
for (int i = 0; i < arrayReading.Length; i++)
{
if (arrayReading[i].Contains("takefromhere"))
{
result.Add(arrayReading[i]);
if (!arrayReading[i + 1].Contains("dont'ttakefromhere"))
{
result.Add(arrayReading[i + 1]);
if (!arrayReading[i + 2].Contains("dont'ttakefromhere"))
{
rescription.Add(arrayReading[i + 1]);
}
}
}
}
Seems working but it's not really dynamic as I want it, because maybe I need to take 20 values between "takefromhere" and "don'ttakefromhere".
When querying you can try Linq:
using System.Linq;
...
List<string> result = arrayReading
.SkipWhile(item => item != "takefromhere")
.TakeWhile(item => item != "dont'ttakefromhere")
.ToList();
Or if you want good old loop solution:
List<string> result = new List<string>();
bool taking = false;
foreach (string item in arrayReading) {
if (!taking)
taking = item == "takefromhere";
if (taking) {
if (item == "dont'ttakefromhere")
break;
result.Add(item);
}
}
Let's have a look:
Console.Write(string.Join("; ", result));
Outcome:
takefromhere; keeptaking; keeptaking
Please help me. I'm stuck on my array case. I'm newbie on this. Espesially to get array more than 2 variables. I had already browsing into google but i didn't got what i want, and now I've got stuck on it :(
I have array like this
string[] receive = receiveattachment.Split(new char[] { ',' });//{1,0,1,0}
string[] display = isdisplaytotal.Split(new char[] { ',' });//{1,1,1,0}
string[] ccTemp = cc.Split(new char[] { ',' });//{a#gmail.com, b#gmail.com, c#gmail.com, d#gmail.com}
First of all i got the same value from receive and display by this
foreach (var receive_ in receive)
{
foreach (var display_ in display)
{
if (receive_ == display_)
{
//do something
}
}
}
then my problem is, how to get a#gmail.com, c#gmail.com ?
I tried like this
foreach (var receive_ in receive)
{
foreach (var display_ in display)
{
if (receive_ == display_)
{
string[] ccTemp = cc.Split(new char[] { ',' });
for (int i = 0; i < receive.Length; i++)
{
if (receive[i] == "1")
{
if (_ccIsReceiveAndDisplay.Trim() != "") _ccIsReceiveAndDisplay += ",";
_ccIsReceiveAndDisplay += ccTemp[i];
}
else
{
if (_ccIsReceiveAndDisplay.Trim() != "") _ccIsReceiveAndDisplay += ",";
_ccIsReceiveAndDisplay += ccTemp[i];
}
}
}
}
}
but it will got only receive = 1 value. not receive 1 and display =1
If all the arrays are the same length, use for and an index.
Like this:
for (var index=0; index<receive.length; index++)
if (receive[index] == "1" && display[index] == "1")
DoSomethingWithEmail( ccTemp[index] )
This is also faster, because it loops through the array only once, not once per element in the array.
As a bonus, get the emails the linq-way:
receive.Zip(display, (a,b) => new {A=a, B=b}).Zip(ccTemp, (ab,c) => new {use=ab.A=="1"&&ab.B=="1", email=c}).Where( x=> x.use ).Select( x => x.email)
I've got two string arrays. I want to select one element from the first array and compare to each element of the second array. If element from first array exist in elements of second array i whant to write for example ("Element exist") or something like this.
This should be possible to do with two for loops ?
EDIT
Ok i finaly achived what i wanted usign this code:
string[] ArrayA = { "dog", "cat", "test", "ultra", "czkaka", "laka","kate" };
string[] ArrayB = { "what", "car", "test", "laka","laska","kate" };
bool foundSwith = false;
for (int i = 0; i < ArrayA.Length; i++)
{
for (int j = 0; j < ArrayB.Length; j++)
{
if (ArrayA[i].Equals(ArrayB[j]))
{
foundSwith = true;
Console.WriteLine("arrayA element: " + ArrayA[i] + " was FOUND in arrayB");
}
}
if (foundSwith == false)
{
Console.WriteLine("arrayA element: " + ArrayA[i] + " was NOT found in arrayB");
}
foundSwith = false;
}
I hope this will help others who will want to compare two arrays ;). its all about this foundSwitch. Thx for help once again.
foreach (string str in yourFirstArray)
{
if (yourSearchedArray.Contains(str))
{
Console.WriteLine("Exists");
}
}
foreach (string str in strArray)
{
foreach (string str2 in strArray2)
{
if (str == str2)
{
Console.WriteLine("element exists");
}
}
}
Updated to display when string does not exist in strArray2
bool matchFound = false;
foreach (string str in strArray)
{
foreach (string str2 in strArray2)
{
if (str == str2)
{
matchFound = true;
Console.WriteLine("a match has been found");
}
}
if (matchFound == false)
{
Console.WriteLine("no match found");
}
}
Or another way of doing this in less lines of code:
foreach (string str in strArray)
{
if(strArray2.Contains(str))
{
Console.WriteLine("a match has been found");
}
else
{
Console.WriteLine("no match found");
}
}
You can also try:
ArrayA.All(ArrayB.Contains);
How would like to to compare values in this nested foreach.
I want to compare and if they match print YES for example.
Cheers
using System;
class Program
{
static void Main()
{
// Use a string array to loop over.
string[] ferns =
{
"apple",
"Equisetopsida",
"Marattiopsida",
"Polypodiopsida"
};
string[] fruits=
{
"apple",
"mango",
"Marattiopsida",
"Polypodiopsida"
};
// Loop with the foreach keyword.
foreach (string value in ferns)
{
Console.WriteLine(value);
foreach (string value in fruits)
{
Console.WriteLine(value);
}
//I would like to compare values here.
//Compare frens values against fruits values.
//How can i achieve this
}
}
}
foreach (string fern in ferns)
{
Console.WriteLine(fern);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
if(fruit.Equals(fern))
Console.WriteLine("YES");
}
}
value is not a keyword here(through it is in some circumstances). All you have to do is pick whatever variable name you like
Do you want to compare them to see if they match in order? Or just if one list contains the other one at all?
If order counts, loop through both at same time with counter variable (just needs boundary checks):
for (int x = 0; x < ferns.Length; x++)
{
if (ferns[x] == fruits[x])
{
Console.WriteLine("YES!");
}
}
If it just needs to contain it:
foreach (string fern in ferns)
{
if (fruits.Contains(fern))
Console.WriteLine("YES!");
}
This would also be a good place to use an intersection. An intersection takes two lists and returns all the items that 'both' lists have in common.
IEnumerable<string> commonWords = ferns.Intersect(fruits);
Option A
foreach (string fernsvalue in ferns)
{
foreach (string fruitsvalue in fruits)
{
if (fernsvalue.Equals(fruitsvalue))
Console.WriteLine("They are equal");
}
}
Option B
List<string> fernsList = new List<string>(ferns.Length);
List<string> fruitsList = new List<string>(fruits.Length);
fernsList.AddRange(ferns);
fruitsList.AddRange(fruits);
List<string> Differences = fernsList.Except(fruitsList).ToList();
Option C
bool equal = ferns.SequenceEqual(fruits); //compares for exact equality
first of all, in each of yours foreach, current element has this same name, and you will not be able to reach botch of them in second foreach.
To compare two string, you can use String.Compare method. For example:
foreach (string fern in ferns)
{
foreach (string fruit in fruits)
{
if(String.Compare(fern,fruit,false)==0)
{
Console.WriteLine("YES");
}
}
}
Are you trying to see if the elements in the arrays fruits and ferns match at the same index? If so then a nested foreach loop isn't the best way to achieve this. It's much easier to use a for loop
for (int i = 0; i < ferns.Length && i < fruits.Length; i++) {
if (fruits[i] == ferns[i]) {
Console.WriteLine("{0} YES!!!", fruits[i]);
}
}
If instead you're looking to see if there is any match at all for an element in the ferns array in the fruits array then you could try the following
foreach (string fern in ferns) {
Console.Write("{0} ", fern);
bool isMatch = false;
foreach (string fruit in fruits) {
if (fruit == fern) {
isMatch = true;
break;
}
}
Console.WriteLine(isMatch ? "YES" : "NO");
}