How to convert collection arrays to list<> C# - c#

I have several arrays to collect data from a postgreSQL query. The data comes from RF receiver deployed in the field. As the user establishes the range of frequencies and time for the query the data is displayed on gridview and passed from there to the arrays indicated by an I value and a I + value matching the cell number in the column containing the latitude of the RF receiver. This data is use to plot xy scatter graphs representing (frequency,amplitude), (frequency,bandwidth) etc. I would like to create a list and objects instead of using arrays.
private void button11_Click(object sender, EventArgs e)
dataGridView1.SelectAll();
numCells = dataGridView1.SelectedCells.Count;
for (i = 14; i < (numCells); i += 14)
{
if (i < numCells)
{
if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()== 28.464258839)
{
UCS1size += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.42859146)
{
MOCsize += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.490616471)
{
AMsize += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.525409911)
{
UCS2size += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToStrin()) == 28.560529988)
{
LC40size += 1;
}
}
else
{
MessageBox.Show("exiting for loop. numcells: " + numCells);
}
}
double[] freqLC40 = new double[LC40size];
double[] ampMaxLC40 = new double[LC40size];
double[] freqMOC = new double[MOCsize];
double[] ampMaxMOC = new double[MOCsize];
double[] freqUCS1 = new double[UCS1size];
double[] ampMaxUCS1 = new double[UCS1size];
double[] freqUCS2 = new double[UCS2size];
double[] ampMaxUCS2 = new double[UCS2size];
double[] freqAM = new double[AMsize];
double[] ampMaxAM = new double[AMsize];
int LC40idx = 0;
int MOCidx = 0;
int UCS1idx = 0;
int UCS2idx = 0;
int AMsidx = 0;
for (i = 14; i < (numCells); i += 14)
{
if (i < numCells)
{
if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString())== 28.464258839)
{
freqUCS1[UCS1idx] = Convert.ToDouble(dataGridView1.SelectedCell[i].Value.ToString());
ampMaxUCS1[UCS1idx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
UCS1idx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i +11].Value.ToString()) == 28.42859146)
{
freqMOC[MOCidx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxMOC[MOCidx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
MOCidx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.490616471)
{
freqAM[AMsidx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxAM[AMsidx] = Convert.ToDouble(dataGridView1.SelectedCells[i + 9].Value.ToString());
AMsidx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.525409911)
{
freqUCS2[UCS2idx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxUCS2[UCS2idx] = Convert.ToDouble(dataGridView1.SelectedCells[i +9].Value.ToString());
UCS2idx += 1;
}
else if (Convert.ToDouble(dataGridView1.SelectedCells[i + 11].Value.ToString()) == 28.560529988)
{
freqLC40[LC40idx] = Convert.ToDouble(dataGridView1.SelectedCells[i].Value.ToString());
ampMaxLC40[LC40idx] = Convert.ToDouble(dataGridView1.SelectedCells[i+9].Value.ToString());
LC40idx += 1;
}
}
else
{
MessageBox.Show("exiting for loop. numcells: " + numCells);
}
}
//get XY form LC40
xyForm = new XYplotForm();
xyForm.Plot(freqLC40, ampMaxLC40, "LC-40 Max Amplitude");
xyForm.Show();

Related

trouble with displaying ships names when they are sunk

the problem i'm facing right now is that i don't know how to check on the opponent's move which ships it sinks so i can display a message saying "Your ____ has sunk".
this is the code i have written
namespace Naval
{
public partial class Form2 : Form
{
const int Size_grid = 10;
const int picturebox = 50;
PictureBox[,] playerBoard = new PictureBox[Size_grid, Size_grid];
PictureBox[,] opponentBoard = new PictureBox[Size_grid, Size_grid];
int[,] playerShips = new int[Size_grid, Size_grid];
int[,] opponentShips = new int[Size_grid, Size_grid];
int[] Lengths = new int[] { 5, 4, 3, 2 };
//string[] Names = new string[] { "Αεροπλανοφόρο", "Αντιτορπιλικό", "Πολεμικό", "Υποβρύχιο" };
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
for (int row = 0; row < Size_grid; row++)
{
for (int col = 0; col < Size_grid; col++)
{
PictureBox playerPictureBox = new PictureBox();
playerPictureBox.Size = new Size(picturebox, picturebox);
playerPictureBox.Location = new Point(col * (picturebox + 10) + 185, row * (picturebox + 10) + 245);
playerPictureBox.Click += PictureBox_Click;
playerPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
playerPictureBox.BackColor = Color.Gray;
panel1.Controls.Add(playerPictureBox);
playerBoard[row, col] = playerPictureBox;
}
}
for (int row = 0; row < Size_grid; row++)
{
for (int col = 0; col < Size_grid; col++)
{
PictureBox opponentPictureBox = new PictureBox();
opponentPictureBox.Size = new Size(picturebox, picturebox);
opponentPictureBox.Location = new Point(col * (picturebox + 10) + 1145, row * (picturebox + 10) + 245);
opponentPictureBox.Click += PictureBox_Click;
opponentPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
opponentPictureBox.BackColor = Color.Gray;
panel1.Controls.Add(opponentPictureBox);
opponentBoard[row, col] = opponentPictureBox;
}
}
PlacePlayerShips(playerShips, Lengths);
PlaceOpponentShips(opponentShips, Lengths);
}
private void PictureBox_Click(object sender, EventArgs e)
{
PictureBox pictureBox = (PictureBox)sender;
int row = (pictureBox.Location.Y - 245) / (picturebox + 10);
int col = (pictureBox.Location.X - 1145) / (picturebox + 10);
if (pictureBox.Location.X >= 1145 && pictureBox.ImageLocation == null) // opponent board
{
if (row >= 0 && row < opponentShips.GetLength(0) && col >= 0 && col < opponentShips.GetLength(1))
{
if (opponentShips[row, col] > 0)
{
pictureBox.ImageLocation = "x.png";
}
else
{
pictureBox.ImageLocation = "-.png";
}
ComputerMove();
}
}
}
private void ComputerMove()
{
Random random = new Random();
int row = random.Next(Size_grid);
int col = random.Next(Size_grid);
while (playerBoard[row, col].ImageLocation != null)
{
row = random.Next(Size_grid);
col = random.Next(Size_grid);
}
if (playerShips[row, col] > 0)
{
playerBoard[row, col].ImageLocation = "x.png";
}
else
{
playerBoard[row, col].ImageLocation = "-.png";
}
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void PlacePlayerShips(int[,] playerShips, int[] shipLengths)
{
Random random = new Random(DateTime.Now.Millisecond);
foreach (int shipLength in shipLengths)
{
int row, col;
int direction = random.Next(2);
int placed = 0;
while (placed == 0)
{
if (direction == 0) // Horizontal
{
row = random.Next(Size_grid);
col = random.Next(Size_grid - shipLength + 1);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (playerShips[row, col + i] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
playerShips[row, col + i] = 1;
playerBoard[row, col + i].BackColor = Color.LightBlue;
}
}
}
else // Vertical
{
row = random.Next(Size_grid - shipLength + 1);
col = random.Next(Size_grid);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (playerShips[row + i, col] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
playerShips[row + i, col] = 1;
playerBoard[row + i, col].BackColor = Color.LightBlue;
}
}
}
// Change direction if ship couldn't be placed
if (placed == 0)
{
direction = (direction + 1) % 2;
}
}
}
}
private void PlaceOpponentShips(int[,] opponentShips, int[] shipLengths)
{
Random random = new Random(DateTime.Now.Millisecond);
;
foreach (int shipLength in shipLengths)
{
int row, col;
int direction = random.Next(2);
int placed = 0;
while (placed == 0)
{
if (direction == 0) // Horizontal
{
row = random.Next(Size_grid);
col = random.Next(Size_grid - shipLength + 1);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (opponentShips[row, col + i] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
opponentShips[row, col + i] = 1;
}
}
}
else // Vertical
{
row = random.Next(Size_grid - shipLength + 1);
col = random.Next(Size_grid);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (opponentShips[row + i, col] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
opponentShips[row + i, col] = 1;
}
}
}
// Change direction if ship couldn't be placed
if (placed == 0)
{
direction = (direction + 1) % 2;
}
}
}
}
private void label1_Click(object sender, EventArgs e)
{
}
int time = 0;
private void timer1_Tick(object sender, EventArgs e)
{
time++;
label42.Text= time.ToString();
}
private void timer2_Tick(object sender, EventArgs e)
{
label44.Text = " ";
timer2.Enabled = false;
}
}
}
i tried adding a switch with choices 1-4 but it didn't work i've also tried having a int[] ship Hits = new int[] {0,0,0,0} and just adding 1 every time a ship was hit but that didn't go as planned because i didn't know how to bind each item of the array to a ship . and i think that's about it
One approach that you might find helpful would be to bundle up all the information about a Ship into a class. This is an abstraction that could make it easier for displaying ship names when they are sunk. At the same time, use inheritance so that a Ship is still a PictureBox with all the functionality that implies.
Ship minimal class example
Member properties tell us what we need know about a ship. Use enum values to make the intent perfectly clear.
class Ship : PictureBox
{
#region P R O P E R T I E S
[Description("Type")]
public τύπος τύπος
{
get => _τύπος;
set
{
if (!Equals(_τύπος, value))
{
_τύπος = value;
switch (_τύπος)
{
case τύπος.Αεροπλανοφόρο: Image = Image.FromFile(Path.Combine(_imageDir, "aircraft-carrier.png")); break;
case τύπος.Αντιτορπιλικό: Image = Image.FromFile(Path.Combine(_imageDir, "destroyer.png")); break;
case τύπος.Πολεμικό: Image = Image.FromFile(Path.Combine(_imageDir, "military.png")); break;
case τύπος.Υποβρύχιο: Image = Image.FromFile(Path.Combine(_imageDir, "submarine.png")); break;
}
}
}
}
τύπος _τύπος = 0;
public bool Sunk { get; set; }
[Description("Flag")]
public σημαία σημαία
{
get => _σημαία;
set
{
_σημαία = value;
onUpdateColor();
}
}
σημαία _σημαία = σημαία.Player;
#endregion P R O P E R T I E S
private void onUpdateColor()
{
var color =
Sunk ? Color.Red :
σημαία.Equals(σημαία.Player) ?
Color.Navy :
Color.DarkOliveGreen;
for (int x = 0; x < Image.Width; x++) for (int y = 0; y < Image.Height; y++)
{
Bitmap bitmap = (Bitmap)Image;
if (bitmap.GetPixel(x, y).R < 0x80)
{
bitmap.SetPixel(x, y, color);
}
}
Refresh();
}
public Point[] Hits { get; set; } = new Point[0];
public override string ToString() =>
$"{σημαία} {τύπος} # {((TableLayoutPanel)Parent)?.GetCellPosition(this)}";
private readonly static string _imageDir =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
}
Where enum values are:
enum Direction
{
Horizontal,
Vertical,
}
enum τύπος
{
[Description("Aircraft Carrier")]
Αεροπλανοφόρο = 5,
[Description("Destroyer")]
Αντιτορπιλικό = 4,
[Description("Military")]
Πολεμικό = 3,
[Description("Submarine")]
Υποβρύχιο = 2,
}
/// <summary>
/// Flag
/// </summary>
enum σημαία
{
Player,
Opponent,
}
Displaying ships names when they are sunk
When the inherited Ship version of PictureBox is clicked the information is now available.
private void onAnyShipClick(object sender, EventArgs e)
{
if (sender is Ship ship)
{
MessageBox.Show(ship.ToString());
}
}
Images credit: Robuart
Used under license.

Chart not labeling entire X Axis (dynamic)

I am trying to display points from 7 files. Each file corresponds to a day, and I am trying to add a button where it takes the last 7 created files and displays them as x=dateTime and y= value. what this code currently does is that only displays the x axis on the left and right side.
private void button1_Click(object sender, EventArgs e)
{
chart1.Titles.Clear();
chart1.Series.Clear();
xAxis.Clear();
yAxis.Clear();
var Series1 = new Series
{
Name = comboBox2.Text,
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Area
};
this.chart1.Series.Add(Series1);
double measur = 0;
//clear graph
string Folder = #"\\Engineer\DI-808\outlooktest\";
var files = new DirectoryInfo(Folder).GetFiles("*_*");
string latestfile = "";
DateTime lastModified = DateTime.MinValue;
List<string> filesD = new List<string>();
DateTime endDate=DateTime.Now;
DateTime startDate= DateTime.Now.AddDays(-3);
DateTime dateToCheck;
Console.WriteLine(startDate + " " + endDate);
foreach (FileInfo file in files)
{
//Console.WriteLine(file.Name+"before");
string edited = file.Name.Remove(0, 6);
//Console.WriteLine(edited+"during");
char[] csv = { '.', 'c', 's', 'v'};
edited = edited.TrimEnd(csv);
//Console.WriteLine(edited + "after CSV");
edited = edited.Remove(10, 9);
// Console.WriteLine(edited+"after");
dateToCheck = Convert.ToDateTime(edited);
Console.WriteLine(dateToCheck+" date to check");
Console.WriteLine(startDate+" start");
Console.WriteLine(endDate+ " end" );
// if ( DateTime.Compare(dateToCheck,startDate)>=0dateToCheck >= startDate && dateToCheck <= endDate);
if (DateTime.Compare(dateToCheck, startDate)>=0 && DateTime.Compare(dateToCheck, endDate)<=0)
{
latestfile = file.Name;
filesD.Add(latestfile);
Console.WriteLine(latestfile+" dweeb");
}
}
Console.WriteLine(filesD.Count());
for (int i = 0; i < filesD.Count(); i++)
Console.WriteLine(files[i]);
string lineData;
try
{
for (int i=0;i<filesD.Count();i++) {
readData = new StreamReader(#"\\egvfps1.egv.mapes.local\Engineer\DI-808\outlooktest\" + filesD[i]);
for (int k = 0; k < 21; k++)
readData.ReadLine();
while ((lineData = readData.ReadLine()) != null)
{
if (Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) <= 0.001)
measur = 0;
else
{
measur = Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) * 110;
xAxis.Add(Convert.ToDateTime(lineData.Split(',')[1]));
yAxis.Add(measur);
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
readData.Close();
this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
this.chart1.Titles.Add(comboBox2.Text + "(" + xAxis[0].ToString("MM/dd/yyyy") + ")");
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
for (int i = 0; i < xAxis.Count(); i++)
{
chart1.Series[comboBox2.Text].Points.AddXY(xAxis[i], yAxis[i]);
}
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series[0].XValueType = ChartValueType.DateTime;
}
enter image description here
I know its somewhere in the Xaxis interval type part,but I don't know what values to put in.
Any suggestions helps!

Cosine similarity calculation issue

I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.

After changing tabpage, the combobox crashes

I have a combobox outside my tabcontrol. In each tab control there is a datagridview full of values. In the combobox you can choose a conversion for all values. For example eV→meV.
When i am in the first tab and use the combobox there are no problems, but after i switch the tab and then wanna use the combobox the program list down however the whole combobox is full of try/catch
private void OpenB_Click(object sender, EventArgs e)
{
string[] result = new string[2];
bool lesen = false;
int Spalte = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Datagridview will be rested, so all values and rows are removed
for (int i = 1; i < Anzahl; i++)
{
DGV[i].Rows.Clear();
}
Anzahl = openFileDialog1.FileNames.Length;
counter = new int[Anzahl];
try
{
if (tabControl1.TabCount < Anzahl)
{
for (int i = 1; i <= Anzahl; i++)
{
if (i > tabControl1.TabCount)
{
string title = "Tab " + (tabControl1.TabCount + 1).ToString();
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
DataGridView NewDGV = new DataGridView();
NewDGV.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
NewDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
NewDGV.Columns.Add("Energy", "Energy");
NewDGV.Columns[0].ReadOnly = true;
NewDGV.Columns.Add("Count Rate", "Count Rate");
NewDGV.Columns[1].ReadOnly = true;
NewDGV.Location = new System.Drawing.Point(3, 3);
NewDGV.Name = "NewDGV" + Convert.ToString(i);
NewDGV.RowHeadersVisible = false;
NewDGV.Size = new System.Drawing.Size(276, 379);
NewDGV.TabIndex = i;
foreach (DataGridViewColumn col in NewDGV.Columns)
col.SortMode = DataGridViewColumnSortMode.NotSortable;
NewDGV.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
DGV.Add(NewDGV);
tabControl1.TabPages[i - 1].Controls.Add(NewDGV);
}
}
}
else if (tabControl1.TabCount > Anzahl)
{
for (int i = tabControl1.TabCount - 1; i >= Anzahl; i--)
{
tabControl1.TabPages.Remove(tabControl1.TabPages[i]);
}
}
}
catch { }
try
{
//Double arrays and Datagridview will be attuned to the count of data
eV = new double[openFileDialog1.FileNames.Length][];
meV = new double[openFileDialog1.FileNames.Length][];
cm = new double[openFileDialog1.FileNames.Length][];
CR = new double[openFileDialog1.FileNames.Length][];
CRmax = new double[openFileDialog1.FileNames.Length][];
for (int i = 0; i < Anzahl; i++)
{
//Naming the columns after data names
string[] Dateiname = openFileDialog1.FileNames[i].Split('\\');
int L = Dateiname.Length;
tabControl1.TabPages[i].Text = Dateiname[L-1];
}
}
catch
{
}
//Datafiles will be read one by one
DataRead(result, ref lesen, ref Spalte);
}
}
/// Reading loop
///
/// double[] eV2 = Energy values of the current data file in eV
/// double[] meV2 = Energy values of the current data file in meV
/// double[] cm2 = Energy values of the current data file in cm^-1
/// double[] CR2 = Intensities of the current data file in CR
/// double[] CRmax2 = normalizied Intensities of the current data file in 1/CRmax
private void DataRead(string[] result, ref bool lesen, ref int Spalte)
{
for (Spalte = 0; Spalte < Anzahl; Spalte++)
{
string line;
lesen = false;
counter[Spalte] = 0;
try
{
Ursprung = openFileDialog1.FileNames[Spalte];
//initialize stream reader
System.IO.StreamReader file1 = new System.IO.StreamReader(openFileDialog1.FileNames[Spalte]);
//read line per line in stream reader
while (((line = file1.ReadLine()) != null))
{
counter[Spalte]++;
Count2 = counter[Spalte];
Count2 = Count2 / 2;
try
{
string[] splitter = line.Split(' ');
if ((splitter[0] == "S") && (splitter[1] == "0000"))
{
lesen = true;
counter[Spalte] = 0;
}
if (lesen == true)
{
//Rows will be filled an added with data value strings
if (counter[Spalte] % 2 == 0)
{
result[0] = splitter[2];
}
else
{
result[1] = splitter[2];
dataGridView1.Rows.Add();
DGV[Spalte].Rows.Add();
int Zeile = (counter[Spalte] - 1) / 2;
DGV[Spalte][0, Zeile].Value = result[0];
DGV[Spalte][1, Zeile].Value = result[1];
}
}
}
catch
{
continue;
}
}
//Streamreader is closed
file1.Close();
counter[Spalte] = counter[Spalte] / 2;
//Current datagridviw values are saved in arrays
//The conversions will be calculated and saved in new arrays
//So every unit gets its own array
double[] eV2 = new double[counter[Spalte]];
double[] meV2 = new double[counter[Spalte]];
double[] cm2 = new double[counter[Spalte]];
double[] CR2 = new double[counter[Spalte]];
double[] CRmax2 = new double[counter[Spalte]];
//Conversion calculation
for (int i = 0; i < counter[Spalte]; i++)
{
eV2[i] = Convert.ToDouble(DGV[Spalte][0, i].Value);
CR2[i] = Convert.ToDouble(DGV[Spalte][1, i].Value);
meV2[i] = 1000 * eV2[i];
cm2[i] = 8066 * eV2[i];
}
//Current file's arrays are saved in double arrays
eV[Spalte] = eV2;
CR[Spalte] = CR2;
meV[Spalte] = meV2;
cm[Spalte] = cm2;
for (int i = 0; i < counter[Spalte]; i++)
{
CRmax2[i] = CR2[i] / CR2.Max();
}
CRmax[Spalte] = CRmax2;
//Chosen conversion replaces values in datagridview
if (Hilfe == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV2[i];
}
}
else if (Hilfe == 2)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm2[i];
}
}
if (Hilfe2 == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][1, i].Value = CRmax2[i];
}
}
}
catch
{
MessageBox.Show("Es ist ein Fehler beim Einlesen eingetreten");
}
}
}
/// Energy Unit
/// Choses between eV, meV, 1/cm
/// Datagridview values are replaced by the unit array values
/// Hilfe... Saves current energy unit
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int L = comboBox1.SelectedIndex;
try
{
if (L == 0)
{
Hilfe = 1;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
}
}
catch
{
}
}
if (L == 1)
{
Hilfe = 2;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm[Spalte][i];
}
}
}
catch
{
}
}
if (L == 2)
{
Hilfe = 0;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = eV[Spalte][i];
}
}
}
catch
{
}
}
}
catch { }
}
Accept these answer if you dont know how to post your own answer?.
Answer:
Problem fixed. The reason was the dgv.autosizemode , when i deactivate it before the conversions it runs.
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
}

C# How to exclude an int from an array?

So I've got an array of integer. I want to use a loop and exclude integers that makes the equation true. So that would be like
for (int n = 0; n < first9char.Length; n++ ) {
if (first9char[n] == clickValue) {
first9char[n] = first9char[n + 1];
But then it only changes the value that is equal to not changing whole array. So is there any way to do this?
I want to use it in this loop.
if (UserSquareMethod.clickedBoxes[0] == -1) {
MessageBox.Show("You have not selected any box");
} else {
int i = 0;
do {
if (textButtonArray[clickedBox[i]].Text == "" || clickValue == "") {
textButtonArray[clickedBox[i]].Text = clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 14, FontStyle.Bold);
}
else
{
textButtonArray[clickedBox[i]].Text += "," + clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 5, FontStyle.Regular);
string[] first9char = textButtonArray[clickedBox[i]].Text.Split(new string[] { "," }, StringSplitOptions.None);
for (int j = 1; j < first9char.Length; j++)
{
for (int k = j - 1; k >= 0; k--)
{
if (first9char[j] == first9char[k])
{
if (clearNumberClicked == true)
{
first9char = Array.FindAll(first9char, x => x != clickValue);
label2.Text = first9char[0];
//int n = 0;
//for (int p = 0; p < first9char.Length; p++)
//{
// if (first9char[p] != clickValue)
// {
// first9char[n] = first9char[p];
// n++;
// label2.Text += "," + first9char[n];
// }
// }
//for (int n = 0; n < first9char.Length; n++ ) {
//if (first9char[n] == clickValue) {
// first9char[n] = first9char[n + 1];
// for ( int p = 0; p < n; p++) {
//}
//}
//}
MessageBox.Show("Clear the number" + first9char[(first9char.Length - 1)] + "and " + clickValue + " " + first9char.Length);
}
else {
first9char[j] = "";
textButtonArray[clickedBox[i]].Text = first9char[0];
MessageBox.Show("You cannot enter the same number again!"+ first9char[j]+j);
for (int m = 1; m < (first9char.Length - 1); m++) {
textButtonArray[clickedBox[i]].Text += ","+ first9char[m];
}
}
}
}
}
if (textButtonArray[clickedBox[i]].Text.Length > 9)
{
textButtonArray[clickedBox[i]].Text = first9char[0] + "," + first9char[1] + "," + first9char[2] + "," + first9char[3] + "," + first9char[4];
MessageBox.Show("You cannot enter more than 5 numbers, please clear the box if you want to enter different number." + textButtonArray[clickedBox[i]].Text.Length);
}
}
i++;
}
while (clickedBox[i] != -1);
}
}
I would use LINQ for this:
first9char = first9char.Where(x => x != clickValue).ToArray();
It just means "pick the items that don't match". If you can't use LINQ for some reason, then just keep another counter, and make sure to only loop to n from there on in:
int n = 0;
for(int i = 0; i < first9char.Length; i++) {
if(first9char[i] != clickValue) {
first9char[n] = first9char[i];
n++;
}
}
Clean and efficient.

Categories

Resources