Reducing linq and convert C#2005 - c#

I want to reducing linq code below and convert C# 2005
private void cmdCaculator_Click(object sender, EventArgs e)
{
int rowcount = gridView1.RowCount;
Thread myThr = new Thread(() =>
{
for (int i = 0; i < rowcount; i++)
{
x *=i;
}
});
myThr.Start();
}

There's no LINQ in that code - just a lambda expression. You can use an anonymous method instead:
private void cmdCaculator_Click(object sender, EventArgs e)
{
int rowcount = gridView1.RowCount;
Thread myThr = new Thread(delegate ()
{
for (int i = 0; i < rowcount; i++)
{
x *= i;
}
});
myThr.Start();
}
However, I would strongly recommend that you update your toolchain. By restricting yourself to C# 2 you're missing out on lots of massively useful features.

Related

How to remove even numbers from an arraylist in c#?

So I'm trying to remove all even numbers from the generated random list I created. But this message keeps showing up: "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
I don't know what I'm doing wrong. What do I need to change?
public partial class Form2 : Form
{
ArrayList array = new ArrayList();
int count = -1;
int[] numbers = new int[5];
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random randNum = new Random();
for (int i = 0; i < 5; i++)
{
numbers[i] = randNum.Next(-100, 100);
array.Add(numbers[i]);
richTextBox1.Clear();
}
for (int i = 0; i <= count; i++)
{
//displays random numbers to rich textbox
richTextBox1.AppendText(array[i].ToString() + '\n');
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (int i in array)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Your code in Button2_click is wrong. You are using foreach loop and then trying to access the index of array using its elements value.
change your second button code with following code
for (int i = 0; i < array.Count; )
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
else {
i++;
}
}
foreach (var item in array)
{
richTextBox1.Text = item +"\n";
}
You should change your enumeration like:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < array.Count; i++)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Using LINQ you can achieve this easily.
var oddArray = array.Where(a => a % 2 != 0);
richTextBox1.Text = string.Join(", ", oddArray);
PS - You just need to add a namespace i.e. System.Linq

Program that creates an array of elements obtained from actions on the first matrix and outputs the elements of the array

Create a program that finds all elements in the matrix D(m, n), where the sum of all the elements of the row standing before the one under consideration is greater than the sum of the elements of the column standing before the one under consideration. The sum of the preceding elements is considered equal to zero if the element is the first in a row or column. Form an array from the found elements. Output the matrix as a matrix, and below it output the elements of the array.(Windows Forms application)
It turns out to create the first matrix. I can't create an array according to a given rule. And I can't figure out how to output array elements(not console! its Windows Forms app)
I have been suffering for a week with this task.
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int M = 0;
int N = 0;
int[,] Numbers;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) // create matrix
{
dataGridView1.Columns.Clear();
dataGridView1.Rows.Clear();
dataGridView1.AllowUserToAddRows = true;
M = int.Parse(M_input.Text);
N = int.Parse(N_input.Text);
Numbers = new int[0, 0];
Numbers = new int[N, M];
for (int i = 0; i < M; i++)
{
dataGridView1.Columns.Add("", "");
}
for (int i = 0; i < N; i++)
{
dataGridView1.Rows.Add("", "");
}
dataGridView1.AllowUserToAddRows = false;
}
//this button should create an array and output array elements (in the form of a string, most likely)
private void button2_Click(object sender, EventArgs e)
{
int n = dataGridView1.RowCount;
int m = dataGridView1.ColumnCount;
double[,] array1 = new double[n, m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
array1[i, j] = double.Parse(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
int times = 0;
dataGridView2.RowCount = 1;
dataGridView2.ColumnCount = 0;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++)
{
double sum1 = 0;
double sum2 = 0;
if (i == 0)
sum1 = 0;
else
for (int k = 0; k < i; k++)
sum1 += array1[i, k];
if (j == 0)
sum2 = 0;
else
for (int k = 0; k < j; k++)
sum2 += array1[k, j];
if (sum1 > sum2)
{
dataGridView2.ColumnCount++;
dataGridView2.Rows[0].Cells[times].Value = array1[i, j];
times++;
}
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void LUM1_Click(object sender, EventArgs e)
{
}
private void LUM2_Click(object sender, EventArgs e)
{
}
private void LUM3_Click(object sender, EventArgs e)
{
}
private void Matrix_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void M_input_TextChanged(object sender, EventArgs e)
{
}
private void N_input_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Matrix2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
}
}
Imagine you have excel open, and you have numbers from 1 to 100 in a 10x10 grid.. A1 is 1, B1 is 2, A2 is 11 etc
Your assignment asks you to pick a cell, say B2. Is the sum of the values in row 1 greater than the sum of the values in column A? Yes-> put the value of B2 in a list. Repeat for another cell. Do all the cells
I started on B2 because it has a row above it and a column to the left of it so it doesn't need to handle that special case of "no row or column means means sum is 0"'that you get for any cell on row 1 or in column A
Make your life easy. Write two Methods:
public int SumColumn(int whichCol)
//if whichCol is -1 return 0
//declare variable to hold the sum
//loop over the grid from [row 0, col whichCol] to [row N, col whichCol], adding up into sum
//return sum
public int SumRow(int which)
//copy paste and adapt code above to work across rows not down columns
Now check your grid
//declare a list to hold the cells we find with SumRow>SumColumn
//for r in rows
//for c in columns
//add current cell value to a textbox ("output the matrix")
//if SumRow(r-1) > SumColumn(c-1)
//add to list
//add the contents of the list to the TextBox too with another loop
Should take about 15 minutes to write this code, not weeks. The design process for code when you're unfamiliar with anything is like I have done here. Write comments in the language you think in; get the algorithm straight in your mind and written down before you start hacking out code and getting lost. The comments are your direction, your essay plan, the recipe book while everything in the kitchen is going crazy. You absolutely have to plan your programs just like when you speak a foreign language; first you imagine the sentence you want to say in your native language, then maybe you rearrange it to how the foreigners say it (word order), then you translate the words and conjugate, modify etc, then finally you speak it. Engaging in that translation process for English->C# is the same; you know one language but not the other
When you're done, leave the comments in so if you went wrong you can either see it and fix it or your supervisor can see where your thinking and your c# understanding diverged, give you points for the algorithm and know what to teach you to help with where it went wrong
I have solved the problem
Image of matrix
namespace Matrix
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int m; // columns
int n; // rows
int[,] MatrixArray; // array of matrix elements
private void Create_Click(object sender, EventArgs e)// By clicking, a matrix grid is created
{
GridMatrix.AllowUserToAddRows = true;
m = int.Parse(Size_M.Text); // Enter the number of columns
n = int.Parse(Size_N.Text); // Enter the number of rows
_Answer.Text = "Elements (answer):";
GridMatrix.Columns.Clear();
GridMatrix.Rows.Clear();
MatrixArray = new int[n, m]; // Creating an empty array of dimension m x n
for (int i = 0; i < m; i++)// Creating columns
{
GridMatrix.Columns.Add("", "");
}
for (int i = 0; i < n; i++)// Creating rows
{
GridMatrix.Rows.Add("", "");
}
GridMatrix.AllowUserToAddRows = false;
}
private void Answer_Click(object sender, EventArgs e)// When pressed, the answer appears
{
for(int i = 0; i < n; i++)// Transferring a matrix to an array
{
for(int j = 0; j < m; j++)
{
MatrixArray[i, j] = int.Parse(GridMatrix[j, i].Value.ToString());
}
}
int[] AnswerArray=new int[m*n];
int Counter=0;
for (int i = 0; i < n; i++) // The algorithm for finding elements
{
for (int j = 0; j < m; j++)
{
int RowSumm = 0,ColumnSumm=0; // Sums of row and column elements
for (int b=0;b<j;b++)// Sum of rows
{
RowSumm += MatrixArray[i, b];
}
for(int b = 0; b < i; b++)// Sum of columns
{
ColumnSumm += MatrixArray[b, j];
}
if (RowSumm>ColumnSumm)
{
AnswerArray[Counter] = MatrixArray[i, j];
Counter++;
}
}
}
_Answer.Text = "Elements (answer):";
for (int i=0;i<Counter;i++)// Output of array elements in turn
{
_Answer.Text += ""+AnswerArray[i];
if (i!=Counter-1)
{
_Answer.Text += ", ";
}
}
}
private void M_Label_Click(object sender, EventArgs e)
{
}
private void N_Label_Click(object sender, EventArgs e)
{
}
private void Answ1_Click(object sender, EventArgs e)
{
}
private void GridMatrix_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void SizeLabel_Click(object sender, EventArgs e)
{
}
private void Size_M_TextChanged(object sender, EventArgs e)
{
}
private void Size_N_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

How to find maximum value from datagridview and display them? and how to label the maximum value on the graph in c#?

I am a really beginner in c#, all this code I just follow tutorial from youtube but now i dont find any tutorial on how to find the maximum value from datagridview and label them on the graph. PLease help me by share the code.
This is what i want, the data is on the left. i want to the display the max. value and the label it on the graph.
private void Form1_Load(object sender, EventArgs e)
{
table.Columns.Add("X Pos (mm)", typeof(double));
table.Columns.Add("Power (mWs)", typeof(double));
dataGridView1.DataSource = table;
}
private void button1_openfile_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(#"C:\Users\Siti Nurhazwani\Desktop\table.txt");
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('/');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
table.Rows.Add(row);
}
}
private void button2_visualize_Click(object sender, EventArgs e)
{
var chart = chart1.ChartAreas[0];
chart.AxisX.IntervalType = DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisX.LabelStyle.IsEndLabelVisible = true;
int rowcount = dataGridView1.RowCount - 1;
double c1 = 0, c2 = 0;
for (int i = 1; i < rowcount; i++)
{
c1 = Convert.ToDouble(dataGridView1.Rows[i].Cells[0].Value);
c2 = Convert.ToDouble(dataGridView1.Rows[i].Cells[1].Value);
chart1.Series["Signal"].Points.AddXY(c1, c2);
}
}
}
}
have you seen https://1bestcsharp.blogspot.com/2016/04/csharp-datagridview-maximum-column-value.html ?
I wish you much success and patience :D
Convert Options:
1 (Step by Step);
// Convert String Array into double[]
double[] xs = Array.ConvertAll(c0, double.Parse);
2(for loop);
*your_variable*.Add(Array.ConvertAll(DataSeries[i], double.Parse));

How can I parallelise this C# algorithm?

I am a beginner C# coder so I don't know anything about Task or threads. I wrote this code and I want to use some kind of Parallel or Thread processing.
The code consist in two DataTable (A & B) and I have to compare each cell value of A to all cells of B. B consist in one column and several rows. A can be millions of cells. I do it using for loops. this is the part of the code I would like to parallelize to speed up the process:
private DataTable CalculosPrincipales(DataTable Prof, DataTable Prop, DataTable Rango)
{
DataTable dt = new DataTable();
dt.Columns.Add("Prof Evaluar", typeof(double));
dt.Columns.Add("Profundidad", typeof(double));
dt.Columns.Add("Promedio", typeof(double));
dt.Columns.Add("Sumatoria", typeof(double));
dt.Columns.Add("n", typeof(double));
if (int.TryParse(box_Z.Text, out int z))
{
}
var step = (progressBar.Properties.Maximum - (Int32)progressBar.EditValue)/z;
for (int i = 0; i < Rango.Rows.Count-1; i++)
{
dt.Rows.Add(Rango.Rows[i][0], Rango.Rows[i][1], 0, 0 , 0);
}
double prof_celda;
double prof_rango;
double prop_celda;
for (int i = 0; i < Prop.Rows.Count; i++)
{
for (int j = 0; j < Prop.Columns.Count; j++)
{
prop_celda = Convert.ToDouble(Prop.Rows[i][j]);
if (prop_celda != nullvalue)
{
for (int k = 0; k < Rango.Rows.Count; k++)
{
prof_celda = Convert.ToDouble(Prof.Rows[i][j]);
prof_rango = Convert.ToDouble(Rango.Rows[k][0]);
if (prof_celda < prof_rango)
{
dt.Rows[k][3] = Convert.ToDouble(dt.Rows[k][3]) + prop_celda;
dt.Rows[k][4] = Convert.ToInt32(dt.Rows[k][4]) + 1;
break;
}
}
}
}
progressBar.PerformStep();
Application.DoEvents();
}
for (int i = 0; i < dt.Rows.Count; i++)
{
if (Convert.ToInt32(dt.Rows[i][4]) == 0)
{
dt.Rows[i].Delete();
i -= 1;
}
}
return dt;
}
This code runs fast if tabla A has 10000 of cells, it takes 5 min when 200000 cells and 20 min when 1000000.
This is an example of parallelisation of your algorithm. However, using the DataTable introduces some performance penalties. You should consider using more suitable classes.
I made the following changes:
Extracted the calculation into a separate class.
Split the calculation into n tasks.
Added support for cancellation via CancellationTokenSource
Replaced active progress reporting with passive one.
Added exception handling
Everything now works in the background. You no longer block or slow down the UI, you just execute the calculation and let it call you back when it finishes.
You can set the number of threads manually, or you can let the algorithm use the the number of CPU cores, which maximizes the performance.
Please note that it's not an ideal implementation, it's just an an example and it's not tested.
It seems to me, that your description does not quite match the code (you talked about 2 input tables, but the code works with 3 - aren't Prop and Prof the same?)
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
public class ParallelCalculation
{
public delegate void CompletionHandler(DataTable result, Exception exception);
public DataTable Prof, Prop, Rango;
class Part
{
public DataTable Result;
public int FromRow, ToRow;
public float Progress;
public Exception Exception;
}
DataTable result;
Part[] parts;
Task[] tasks;
CancellationToken cancellation;
CompletionHandler callback;
public async void Run(CompletionHandler callback, CancellationToken token, int threadCount = 0)
{
this.cancellation = token;
this.callback = callback;
await Task.Factory.StartNew(Perform, threadCount);
}
async void Perform(object state)
{
int threadCount = (int)state;
try
{
// Create table for results
result = new DataTable();
result.Columns.Add("Prof Evaluar", typeof(double));
result.Columns.Add("Profundidad", typeof(double));
result.Columns.Add("Promedio", typeof(double));
result.Columns.Add("Sumatoria", typeof(double));
result.Columns.Add("n", typeof(double));
for (int i = 0; i < Rango.Rows.Count; i++)
result.Rows.Add(Rango.Rows[i][0], Rango.Rows[i][1], 0, 0, 0);
// Split calculation into n tasks. Tasks work in parallel,
// each one processes it's own stripe of data, defined by the instance of the Part class.
int n = threadCount > 0 ? threadCount : Environment.ProcessorCount;
tasks = new Task[n];
parts = new Part[n];
int rowsPerTask = Prof.Rows.Count / n;
int rest = Prof.Rows.Count % n;
for (int i = 0, from = 0, to = 0; i < n; ++i, --rest, from = to)
{
to = from + rowsPerTask + (rest > 0 ? 1 : 0);
parts[i] = new Part { FromRow = from, ToRow = to };
tasks[i] = Task.Factory.StartNew(CalculatePart, parts[i]);
}
// Wait until all partial calculations are finished
await Task.WhenAll(tasks);
// Sum partial results to the main result table (and find the first exception, if any)
Exception e = null;
foreach (var part in parts)
{
e = e ?? part.Exception;
for (int row = 0; row < result.Rows.Count; ++row)
{
result.Rows[row][3] = Convert.ToDouble(result.Rows[row][3]) + Convert.ToDouble(part.Result.Rows[row][3]);
result.Rows[row][4] = Convert.ToInt32(result.Rows[row][4]) + Convert.ToInt32(part.Result.Rows[row][4]);
}
}
// Remove empty rows from results
for (int i = 0; i < result.Rows.Count; i++)
{
if (Convert.ToInt32(result.Rows[i][4]) == 0)
{
result.Rows[i].Delete();
i -= 1;
}
}
// Call back
callback?.Invoke(result, e);
}
catch (Exception e)
{
callback?.Invoke(null, e);
}
}
void CalculatePart(object state)
{
var part = (Part)state;
try
{
// Create our own table for partial results.
part.Result = this.result.Copy();
var result = part.Result; // Just a shortcut
int cols = Prop.Columns.Count;
int steps = cols * (part.ToRow - part.FromRow);
for (int i = part.FromRow, step = 1; i < part.ToRow; i++)
{
for (int j = 0; j < cols; j++, step++)
{
var prop_celda_obj = Prop.Rows[i][j];
if (prop_celda_obj != DBNull.Value)
{
double prop_celda = Convert.ToDouble(prop_celda_obj);
double prof_celda = Convert.ToDouble(Prof.Rows[i][j]);
for (int k = 0; k < Rango.Rows.Count; k++)
{
//double prof_celda = Convert.ToDouble(Prof.Rows[i][j]);
double prof_rango = Convert.ToDouble(Rango.Rows[k][0]);
if (prof_celda < prof_rango)
{
result.Rows[k][3] = Convert.ToDouble(result.Rows[k][3]) + prop_celda;
result.Rows[k][4] = Convert.ToDouble(result.Rows[k][4]) + 1;
break;
}
}
}
part.Progress = step / (float)steps;
if (cancellation.IsCancellationRequested)
return;
}
}
}
catch (Exception e)
{
part.Exception = e;
}
}
public float Progress()
{
float sum = 0.0f;
foreach (var part in parts)
sum += part.Progress;
return sum / parts.Length;
}
}
The following code is an example of using the above class in a Form. You'll have to adapt it a bit, probably.
partial class MyForm {
Button btnStartStop;
ProgressBar progressBar;
// Do this somewhere:
// btnStartStop.Click += BtnStartStop_Click;
int threads = 0; // 0 means "The number of CPU cores"
DataTable Prof, Prop, Rango; // You have to provide these values
// The final results will be stored here:
DataTable Result;
CancellationTokenSource cancellation;
ParallelCalculation calculation;
System.Windows.Forms.Timer progressTimer;
void BtnStartStop_Click(object sender, EventArgs e)
{
if (calculation != null)
cancellation.Cancel();
else
StartCalculation();
}
void StartCalculation()
{
cancellation = new CancellationTokenSource();
calculation = new ParallelCalculation { Prof = this.Prof, Prop = this.Prop, Rango = this.Rango };
calculation.Run(Finished, cancellation.Token, threads);
progressBar.Value = 0;
progressTimer = new System.Windows.Forms.Timer(components) { Interval = 100 };
progressTimer.Tick += ProgressTimer_Tick;
progressTimer.Start();
UpdateUI();
}
void Finished(DataTable table, Exception e)
{
BeginInvoke((Action)delegate
{
Result = table;
progressBar.Value = (int)(calculation.Progress() * 100);
progressTimer.Stop();
progressTimer.Tick -= ProgressTimer_Tick;
calculation = null;
UpdateUI();
});
}
private void ProgressTimer_Tick(object sender, EventArgs e)
{
if (calculation != null)
progressBar.Value = (int)(calculation.Progress() * 100);
}
void UpdateUI()
{
btnStartStop.Text = calculation == null ? "Start" : "Stop";
}
}

How to write lines to a text file thread safe - multi threading

I just tried this and it failed
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
writeFile();
});
}
TextWriter myWriter = new StreamWriter("deneme.txt");
void writeFile()
{
for (int k = 0; k < 10000; k++)
{
int irTempPara = k;
Task.Factory.StartNew(() =>
{
writeFileForReal(irTempPara);
});
System.Threading.Thread.Sleep(10);
}
}
void writeFileForReal(int srParameter)
{
for (int k = 0; k < 999999999; k++)
{
myWriter.WriteLineAsync(srParameter + "_" + k);
}
}
It is c# 4.5 WPF application
So what method would you suggest for writing lines to a text file most effeciently and multi threading
How about this?
TextWriter.Synchronized(myWriter).WriteLine("Hello World!!!");
You can just use simple TPL way as you do, but you can set:
void writeFile()
{
for (int k = 0; k < 10000; k++)
{
int irTempPara = k;
Task.Factory.StartNew(() =>
{
writeFileForReal(irTempPara);
}, TaskCreationOptions.LongRunning); // this way you do not need sleep
// System.Threading.Thread.Sleep(10);
}
}
http://coderkarl.wordpress.com/2012/12/13/long-running-tasks-and-threads/
You must never rely on Sleep for synchronization in multi threading. Instead, take in consideration to use a synchronization mechanism such as a semaphore or a mutex.

Categories

Resources