I have been trying to implement a distributed depth first search in c#. I have beem successful upto a certain point but have got a synchronisation error. I am not able to rectify the error. What i am trying to do is make each node communicate with one other using task parallel dataflow and thereby i attain parallelism in DFS. Below is my code:
public class DFS
{
static List<string> traversedList = new List<string>();
static List<string> parentList = new List<string>();
static Thread[] thread_array;
static BufferBlock<Object> buffer1 = new BufferBlock<Object>();
public static void Main(string[] args)
{
int N = 100;
int M = N * 4;
int P = N * 16;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<string> global_list = new List<string>();
StreamReader file = new StreamReader(args[args.Length - 2]);
string text = file.ReadToEnd();
string[] lines = text.Split('\n');
string[][] array1 = new string[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Trim();
string[] words = lines[i].Split(' ');
array1[i] = new string[words.Length];
for (int j = 0; j < words.Length; j++)
{
array1[i][j] = words[j];
}
}
StreamWriter sr = new StreamWriter("E:\\Newtext1.txt");
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array1[i].Length; j++)
{
if (j != 0)
{
sr.Write(array1[i][0] + ":" + array1[i][j]);
Console.WriteLine(array1[i][0] + ":" + array1[i][j]);
sr.Write(sr.NewLine);
}
}
}
int start_no = Convert.ToInt32(args[args.Length - 1]);
thread_array = new Thread[lines.Length];
string first_message = "root";
buffer1.Post(first_message);
buffer1.Post(array1);
buffer1.Post(start_no);
buffer1.Post(1);
for (int t = 1; t < lines.Length; t++)
{
Console.WriteLine("thread" + t);
thread_array[t] = new Thread(new ThreadStart(thread_run));
thread_array[t].Name = t.ToString();
lock (thread_array[t])
{
Console.WriteLine("working");
thread_array[t].Start();
thread_array[t].Join();
}
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.ReadLine();
}
private static void dfs(string[][] array, int point)
{
for (int z = 1; z < array[point].Length; z++)
{
if ((!traversedList.Contains(array[point][z])))
{
traversedList.Add(array[point][z]);
parentList.Add(point.ToString());
dfs(array, int.Parse(array[point][z]));
}
}
return;
}
public static void thread_run()
{
try
{
string parent;
string[][] array1;
int point;
int id;
parent = (string)buffer1.Receive();
array1 = (string[][])buffer1.Receive();
point = (int)buffer1.Receive();
id = (int)buffer1.Receive();
object value;
Console.WriteLine("times");
if (Thread.CurrentThread.Name.Equals(point.ToString()))
{
if (!traversedList.Contains(point.ToString()))
{
Console.WriteLine("Node:" + point + " Parent:" + parent + " Id:" + id);
traversedList.Add(point.ToString());
parent = point.ToString();
for (int x = 1; x < array1[point].Length; x++)
{
Console.WriteLine("times");
if (buffer1.TryReceive(out value))
{
array1 = (string[][])value;
}
if (buffer1.TryReceive(out value))
{
id = (int)buffer1.Receive();
}
id++;
buffer1.Post(parent);
buffer1.Post(array1);
buffer1.Post(x);
buffer1.Post(id);
Console.WriteLine("times");
Monitor.PulseAll(Thread.CurrentThread);
}
//return;
}
else
{
buffer1.Post(parent);
buffer1.Post(array1);
buffer1.Post(point);
buffer1.Post(id);
Console.WriteLine("working 1");
Monitor.PulseAll(Thread.CurrentThread);
}
}
else
{
Console.WriteLine("working 2");
Monitor.Wait(Thread.CurrentThread);
}
//Console.WriteLine(parent);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
There various issues with your code.
Incorrect use of locking and "touching" the traversedList from multiple threads is the most obvious problem.
More importantly, your code doesn't really use Dataflow, it uses BufferBlock in a manner similar to ConcurrentQueue or any other concurrent collection. The whole point of dataflow is to use ActionBlocks instead of threads to simplify processing. By default an action block will use only a single thread for processing but you can specify as many threads as you want through the DataflowBlockOptions class.
ActionBlocks have their own input and output buffers so you don't have to add additional BufferBlocks just for buffering.
Passing multiple related values to a block is another problem, as it can lead to errors and makes the code confusing. Creating a data structure to hold all the values doesn't cost anything.
Assuming you use this class to hold processing message:
public class PointMessage
{
public string Message { get; set; }
public string[][] Lines{get;set;}
public int Point { get; set; }
public int ID { get; set; }
}
You can create an ActionBlock to process these messages like this:
static ActionBlock<PointMessage> _block;
...
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = ExecutionDataflowBlockOptions.Unbounded };
_block=new ActionBlock<PointMessage>(msg=>ProcessMessage(msg),options);
And process each message like this:
private static void ProcessMessage(PointMessage arg)
{
if (...)
{
...
arg.ID++;
_block.Post(arg);
}
else
{
...
_block.Post(arg);
}
}
If your function returns a value, you can use a TransformBlock instead of an ActionBlock.
I don't understand what your code does so I won't try to rewrite it using DataFlow. If you clean it up a bit, it will be easier to help.
The issue is that the Thread needs to own Monitor in order to call Wait. So you need to lock on Monitor.PulseAll aswell as Monitor.Wait in order to ensure that you don't get any more errors like this.
If you need me to explain locking to you, open another question and I'll explain it in full! :)
EDIT: Ignore my post - Read the post from #PanagiotisKanavos instead...
This won't compile, but will set you in the right direction for using locks:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class DFS
{
static List<string> traversedList = new List<string>();
static List<string> parentList = new List<string>();
static Thread[] thread_array;
//static BufferBlock<Object> buffer1 = new BufferBlock<Object>();
public static void Main(string[] args)
{
int N = 100;
int M = N * 4;
int P = N * 16;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<string> global_list = new List<string>();
StreamReader file = new StreamReader(args[args.Length - 2]);
string text = file.ReadToEnd();
string[] lines = text.Split('\n');
string[][] array1 = new string[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Trim();
string[] words = lines[i].Split(' ');
array1[i] = new string[words.Length];
for (int j = 0; j < words.Length; j++)
{
array1[i][j] = words[j];
}
}
StreamWriter sr = new StreamWriter("E:\\Newtext1.txt");
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array1[i].Length; j++)
{
if (j != 0)
{
sr.Write(array1[i][0] + ":" + array1[i][j]);
Console.WriteLine(array1[i][0] + ":" + array1[i][j]);
sr.Write(sr.NewLine);
}
}
}
int start_no = Convert.ToInt32(args[args.Length - 1]);
thread_array = new Thread[lines.Length];
string first_message = "root";
//buffer1.Post(first_message);
//buffer1.Post(array1);
//buffer1.Post(start_no);
//buffer1.Post(1);
for (int t = 1; t < lines.Length; t++)
{
Console.WriteLine("thread" + t);
thread_array[t] = new Thread(new ThreadStart(thread_run));
thread_array[t].Name = t.ToString();
lock (thread_array[t])
{
Console.WriteLine("working");
thread_array[t].Start();
thread_array[t].Join();
}
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.ReadLine();
}
private static void dfs(string[][] array, int point)
{
for (int z = 1; z < array[point].Length; z++)
{
if ((!traversedList.Contains(array[point][z])))
{
traversedList.Add(array[point][z]);
parentList.Add(point.ToString());
dfs(array, int.Parse(array[point][z]));
}
}
return;
}
bool busy;
private readonly object syncLock = new object();
public static void thread_run()
{
try
{
string parent;
string[][] array1;
int point;
int id;
//parent = (string)buffer1.Receive();
//array1 = (string[][])buffer1.Receive();
//point = (int)buffer1.Receive();
//id = (int)buffer1.Receive();
object value;
Console.WriteLine("times");
if (Thread.CurrentThread.Name.Equals("Point.ToString()"))
{
if (!traversedList.Contains("Point.ToString()"))
{
for (int x = 1; x < 99999; x++)
{
Console.WriteLine("times");
//if (buffer1.TryReceive(out value))
//{
// array1 = (string[][])value;
//}
//if (buffer1.TryReceive(out value))
//{
// id = (int)buffer1.Receive();
//}
//id++;
//buffer1.Post(parent);
//buffer1.Post(array1);
//buffer1.Post(x);
//buffer1.Post(id);
Console.WriteLine("times");
lock (syncLock)
{
while (busy)
{
busy = false;
Monitor.PulseAll(Thread.CurrentThread);
}
busy = true; // we've got it!
}
}
//return;
}
else
{
//buffer1.Post(parent);
//buffer1.Post(array1);
//buffer1.Post(point);
//buffer1.Post(id);
lock (syncLock)
{
while (busy)
{
busy = false;
Monitor.PulseAll(Thread.CurrentThread);
}
busy = true; // we've got it!
}
}
}
else
{
Console.WriteLine("working 2");
lock (syncLock)
{
while (busy)
{
Monitor.Wait(Thread.CurrentThread);
}
busy = true; // we've got it!
}
}
//Console.WriteLine(parent);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Related
The system needs a way of taking input from txtBox.
I then need the system to take the number input, 1-10. And repeat the ticket and file creation for that x amount of times.
This code also creates a file on the pc with the Lottery ticket in it.
the files have to be named LottoKupon1, LottoKupon2 and so on, this needs to match user input of course.
this is for creation of file and folder
namespace Lottery
{
internal class FolderCreater
{
static string folderName = #"C:\lotto";
public static string fileName = #"C:\lotto\LottoKupon.txt";
public static void CreateFolder()
{
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
else if (!File.Exists(fileName))
{
File.Create(fileName);
}
else { }
}
}
}
This is for creation of Lottry Ticket
namespace Lottery
{
// the system needs a way of taking input
// from txtBox, int user = int.Parse(txtBox.Text.Trim()); which this line does
// i then need the system to take the number input, 1-10.
// and repeat the ticket and file creation for that x amount of times.
public partial class MainWindow : Window
{
public List<long> ListOfAllArrays = new List<long>();
int i = 1;
Random randNum = new Random();
public MainWindow()
{
InitializeComponent();
}
public void Lotto ()
{
StreamWriter sw = new StreamWriter(FolderCreater.fileName);
sw.WriteLine(" " + "Lotto " + DateTime.Now.ToString("dd/MM/yyyy\n"));
sw.WriteLine(" " + "1-uge\n" + " LYN-LOTTO\n");
Random randNum = new Random();
int[][] AllArrays = new int[10][];
for (int i = 0; i < 10; i++)
{
AllArrays[i] = new int[7];
}
int RowNr = 0;
foreach (int[] row in AllArrays)
{
RowNr++;
sw.Write(RowNr + ". ");
for (int j = 0; j < 7; j++)
{
int number = randNum.Next(1, 37);
while (row.Any(n => n == number))
{
number = randNum.Next(1, 37);
}
row[j] = number;
}
Array.Sort(row);
for(int l = 0; l < 7; l++)
{
sw.Write(row[l].ToString("00") + " ");
}
sw.Write("\n");
}
TestIfSame(AllArrays);
if (CheckBox.IsChecked == true)
{
sw.WriteLine("\n****** Joker Tal ******");
int[][] AllJokerRows = new int[2][];
for (int i = 0; i < 2; i++)
{
AllJokerRows[i] = new int[7];
}
foreach (int[] n in AllJokerRows)
{
sw.Write(" ");
for (int i = 0; i < 7; i++)
{
var JokerNumber = randNum.Next(1, 10);
n[i] = JokerNumber;
}
Array.Sort(n);
for (int u = 0; u < 7; u++)
{
sw.Write(n[u] + " ");
}
sw.Write("\n");
}
}
sw.Close();
}
public void TestIfSame(int[][] AllArrays)
{
//List<long> ListOfAllArrays = new List<long>();
for (int i = 0; i < AllArrays.Length; i++)
{
ListOfAllArrays.Add(MakesLongNumber(AllArrays[i]));
}
for (int i = 0; i < AllArrays.Length; i++)
{
long temp = ListOfAllArrays[0];
ListOfAllArrays.Remove(ListOfAllArrays[0]);
if (ListOfAllArrays.Contains(MakesLongNumber(AllArrays[i])))
{
Lotto();
}
else
{
ListOfAllArrays.Add(temp);
}
}
long MakesLongNumber(int[] row)
{
string a = "";
for (int i = 0; i < row.Length; i++)
{
a += row[i].ToString();
}
return Convert.ToInt64(a);
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
}
private void cmdOk_Click_1(object sender, RoutedEventArgs e)
{
FolderCreater.CreateFolder();
Lotto();
// add a ListBox.Items.Add(); within this needs to be the command for the Lottery ticket, so i can have it shown on a list box.
}
**This is for a Lottery assignment, its on a lower level of coding, so no answer that is way too complicated, hope you understand. please ask questions if needed.
I tried a dew things with a for loop around the first void which took user input, but i could not make it work.
the code is expected to create files and Lottery ticket depending on users input**
I'm solving my first training task and I'm at a dead end: I don't know how to pass values from List to the Percentile method. I can't figure it out myself. List gets the values from txt, and then passes them to methods for different calculations, such as calculating the percentile. I can't figure out how to link a sheet to a percentile.
using System;
using System.Collections.Generic;
using System.IO;
namespace Fromtxt
{
public class Program
{
public static void Main(string[] args)
{
var filePath = #"C:\Users\Saint\Desktop\text1.txt";
var numbers = NumbersFromTxt(filePath);
}
static List<int> NumbersFromTxt(string filePath)
{
var streamReader = new StreamReader(filePath);
var results = new List<int>();
string line;
while ((line = streamReader.ReadLine()) != null)
{
var isParsed = int.TryParse(line, out var result);
if (!isParsed)
throw new Exception("no");
results.Add(result);
}
return results;
}
private static void Percentile(List<int> list, decimal [] arr)
{
list = new List<int>() { };
{
int n = arr.Length;
for (int i = 0; i < n; i++)
{
decimal count = 0;
for (int j = 0; j < n; j++)
{
if (list[i] > list[j])
{
count++;
}
}
decimal percent = (count * 90) / (n - 1);
Console.WriteLine("\nPercentile of stocks Apple for June "
+ (i + 1) + " = " + percent.ToString("F2"));
}
}
}
}
}
If you call method NumbersFromTxt() only once in Main(), and want to use it results in other methods and you are not going to create another class for them, most preferable decision would be to create a field with this value. In your code it would be
using System;
using System.Collections.Generic;
using System.IO;
namespace Fromtxt
{
public class Program
{
public static void Main(string[] args)
{
var filePath = #"C:\Users\Saint\Desktop\text1.txt";
NumbersFromTxt(filePath);
Percentile();
}
static List<int> results;
static void NumbersFromTxt(string filePath)
{
var streamReader = new StreamReader(filePath);
results = new List<int>();
string line;
while ((line = streamReader.ReadLine()) != null)
{
var isParsed = int.TryParse(line, out var result);
if (!isParsed)
throw new Exception("no");
results.Add(result);
}
}
private static void Percentile()
{
{
int n = results.count;
for (int i = 0; i < n; i++)
{
decimal count = 0;
for (int j = 0; j < n; j++)
{
if (results[i] > results[j])
{
count++;
}
}
decimal percent = (count * 90) / (n - 1);
Console.WriteLine("\nPercentile of stocks Apple for June "
+ (i + 1) + " = " + percent.ToString("F2"));
}
}
}
}
}
If I get you right, you already have almost everything set: you just need to call your Percentile method after you calculated numbers, passing these numbers just as you did with filePath for NumbersFromTxt: Percentile(numbers, arr). (Don't know what arr is for, actually)
The only issue left is that you reassign your list in Percentile method, which makes your initial list "disappear" (list = new List<int>() { };). Consider removing this line.
And I don't think you need arr parameter, as you use it only to get Length. Try list.Count.
so I'm in a bit confused as to how I'm supposed to do something. I've got 5 threads that are doing a basic task and they are generated with a for loop in main. I've already used a semaphore that limits the amount of threads running at a time as that's a part of the exercise, what I've got left is to make sure that threads that are next to each other (they're numbered 0-4 using the loop) don't run simultaneously. What I've got as an idea is to block every odd or even thread(it doesn't really matter) but I can't figure out how to both let two threads in and at the same time block every odd one. Is there a specific method for that, or maybe if there is another way, like letting three in at first and somehow not letting the second one in but letting the third one. I'll leave what I've got done so far:
edit: For clarification the way it has to be thought about is actually a bit different then what I initially asked about. So if 1 is running both 0 and 2 aren't allowed to run. But if 0 is running both 4 and 1 aren't allowed to run either. I'm pretty sure that it's obvious that if 4 is running 0 and 3 aren't allowed to work etc. .
using System.Threading;
namespace StudentProblem
{
public class StudentProblem
{
static Semaphore stop = new Semaphore(2,2);
static Semaphore gate = new Semaphore(3,3);
public static void Student(Object o)
{
var r = new Random();
var num = (int) o;
while (true)
{
Console.WriteLine(" Student " + num + " start learning.");
Thread.Sleep(r.Next(2000, 3000));
for (int i = 0; i < num; i++)
Console.Write("_");
//gate.WaitOne();
stop.WaitOne();
Console.WriteLine("> Student " + num + " start eating.");
Thread.Sleep(r.Next(2000, 3000));
for (int i = 0; i < num; i++)
Console.Write("_");
Console.WriteLine("< Student " + num + " stop eating");
//gate.Release();
stop.Release();
}
}
}
class Program
{
static void Main(string[] args)
{
var studentThreads = new Thread[5];
for (int i = 0; i < 5; i++)
{
studentThreads[i] = new Thread(StudentProblem.Student);
studentThreads[i].Start(i);
}
}
}
}
In the end I decided to ditch the whole multiple semaphore approach and went with the old and trusty way. I'll add my solution here. It's not that great, but it works.
using System;
using System.Collections.Generic;
using System.Threading;
namespace testing
{
public class StudentProblem
{
public static List<StudentProblem> allProblems = new List<StudentProblem>();
static Semaphore eatingGate = new Semaphore(2, 2);
private object id;
private bool eating = false;
public StudentProblem(object o)
{
id = o;
}
public object Id
{
get
{
return this.id;
}
}
public bool Eating
{
get
{
return this.eating;
}
}
public void DoStuff()
{
var r = new Random();
var num = (int)this.Id;
Console.WriteLine(" Student " + num + " start learning.");
Thread.Sleep(r.Next(2000, 3000));
while (true)
{
for (int i = 0; i < num; i++)
Console.Write("_");
int indexBehind = 0;
int indexFront = 0;
for (int i = 0; i < allProblems.Count; i++)
{
if(num == 0)
{
indexBehind = 4;
}
else
{
indexBehind = num - 1;
}
if(num == 4)
{
indexFront = 0;
}
else
{
indexFront = num + 1;
}
check:
if (allProblems[indexBehind].Eating != true && allProblems[indexFront].Eating != true)
{
if (eatingGate.WaitOne())
{
this.eating = true;
Thread.Sleep(250);//poigrai si s timeout-a
Console.WriteLine("> Student " + num + " start eating.");
Thread.Sleep(r.Next(1000, 2000));
for (int j = 0; j < num; j++)
Console.Write("_");
Console.WriteLine("< Student " + num + " stop eating");
this.eating = false;
eatingGate.Release();
Console.WriteLine(" Student " + num + " start learning.");
Thread.Sleep(r.Next(2000, 3000));
}
else
{
goto check;
}
}
else
{
goto check;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
var studentThreads = new Thread[5];
for (int i = 0; i < 5; i++)
{
StudentProblem.allProblems.Add(new StudentProblem(i));
studentThreads[i] = new Thread(StudentProblem.allProblems[i].DoStuff);
studentThreads[i].Start();
}
}
}
}
Trying to build Array of Lists of Structs in C#. And getting a System.NullReferenceException with the best try (error on line test[i].Add(info1);)
The question is not how to avoid System.NullReferenceException at all, but more like how to quickly build Array of Lists with predefined size of array, thus that one is able to use array[i].Add(Struct) in it. If possible without looping all over the array, just to create the lists.
So these are the requirements:
the size of the array should be predefined;
the numbers of the lists per node should be arbitrary, and there should be a possibility that these are added easily;
the structure should contain the struct Info.
This is the code, I have managed so far (copy and paste should work, to replicate the error):
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
test[i].Add(info1);
}
for (int i = 0; i < 1000; i+=5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
test[i].Add(info2);
}
}
struct Info
{
public int capacity;
public string name;
}
}
Each element of a the array are not defined as the object is a List
This is how you should do it :
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
// if null initialise the list
if(test[i] == null) test[i] = new List<Info>();
test[i].Add(info1);
}
for (int i = 0; i < 1000; i+=5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
// if null initialise the list
if(test[i] == null) test[i] = new List<Info>();
test[i].Add(info2);
}
}
struct Info
{
public int capacity;
public string name;
}
}
Try this:
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
test[i] = new List<Info> {info1};
}
for (int i = 0; i < 1000; i += 5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
if (test[i] == null)
{
test[i] = new List<Info> { info2 };
}
else
{
test[i].Add(info2);
}
}
}
struct Info
{
public int capacity;
public string name;
}
}
Try this:
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
var test = Enumerable.Range(0,entry)
.Select(i=> {
var y = new List<Info>();
if(i%3==0 && i < 500)
{
y.Add(new Info {
capacity = i*2,
name = i.ToString()
});
}
if(i%5==0 && i < 1000)
{
y.Add(new Info {
capacity = i*2,
name = i.ToString() + i.ToString()
});
}
return y;
}).ToArray();
}
struct Info
{
public int capacity;
public string name;
}
}
I have an array which can hold 10 elements:
string[] Ar = new string[10];
But it has only 5 items added to it. I need to insert The string value "NULL" to the rest of the empty slots in the array and thus making the array 'full' with string elements (that, being my objective).
This is what I've attempted as of now:
int entityCount = 5;
if (entityCount < 10)
{
for (int i = entityCount; i < 10; i++)
{
Ar[i] = "NULL";
}
}
And thus, when printed should output the values:
A, B, C, D, E, NULL, NULL, NULL, NULL, NULL
But this does not seem to do the trick, Still prints out ONLY the 5 items and not the 5 new strings.
I am not from C# background but I think this is what you want:
string[] Ar = new string[10];
for (int i = 0; i < 10; i++)
{
if(String.IsNullOrEmpty(Ar[i]))
{
Ar[i]="NULL";
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Ar[i]);
}
You can read about String.IsNullOrEmpty(Ar[i]) here.
static void Main(string[] args)
{
int arraySize = 10;
string[] Ar = new string[arraySize];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
for (int i = 0; i < arraySize; i++)
{
if (Ar[i]==null)
{
Ar[i] = "NULL";
}
}
for (int i = 0; i < Ar.Length; i++)
{
Console.Write(Ar[i]+" ");
}
}
}
this works fine.
int entityCount = 5;
string[] Ar = new string[10];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
Ar[4] = "E";
if(entityCount < 10) {
for(int i = entityCount; i < 10; i++) {
Ar[i] = "NULL";
}
}
foreach(string s in Ar) {
Console.WriteLine(s);
}
using System;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
string[] Ar = new string[10];
var item = from f in Ar
select string.IsNullOrWhiteSpace(f) ? "NULL" : f;
foreach (var i in item)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Here item is iterator in string of array replace all with null if not contains value
string multiplayer = new string[5];
foreach (var item in multiplayers)
{
if (item == null) { Console.WriteLine("Empty"); }
Console.WriteLine(item);
}
remember string of array is not nullable here