I'm working on a method that compares a collection of objects (since the object supports all types), if they are all the same, it returns true, but if one or more differs, it returns false.
This is what I have:
public static bool Compare(bool compareTypes = false, params object[] values)
{
if (!compareTypes)
{
if (values is null || values.Length == 0) return false;
else if (values.Length == 1) return true;
else return values[0] == values[1];
}
else
{
if (values is null || values.Length == 0) return false;
else if (values.Length == 1) return true;
else return values[0].GetType() == values[1].GetType();
}
}
And it works fine as long as the number of objects is 2.
My problem is that I want the method to compare the value or the type of all parameters that are passed regardless of the amount
This is what I want my method to do
Compare (false, "Hello", "Hello") //True
Compare(false, "Hello", "Bye") //False
Compare(true, 0, 1) //True
Compare(true, "Hi", 20) //False
Compare(false, "LOL", "LOL", "LOL", "LOL") //True
Compare(false, "LOL", "LOL", "LOL", "lol") //False
If you are ok with the logic that works for 2 objects why not just compare all objects in a same way with a loop?
public static bool Compare(bool compareTypes = false, params object[] values)
{
if (!compareTypes)
{
if (values == null || values.Length == 0)
{
return false;
}
else if (values.Length == 1)
{
return true;
}
else if (values.Length == 2){
return values[0] == values[1];
}
else
{
bool result = true;
for(int i = 0; i < values.Length - 1; i++)
{
if(values[i] != values[i+1])
{
result = false;
break;
}
}
return result;
}
}
else
{
if (values == null || values.Length == 0)
{
return false;
}
else if (values.Length == 1)
{
return true;
}
else if (values.Length == 2)
{
return values[0].GetType() == values[1].GetType();
}
else
{
bool result = true;
for(int i = 0; i < values.Length - 1; i++)
{
if(values[i].GetType() != values[i+1].GetType())
{
result = false;
break;
}
}
return result;
}
}
}
Here is a running example with your test cases : https://dotnetfiddle.net/uDA5Mb
You can also use recursive and simplify your code with that way.
public static bool Compare(bool compareTypes = false, params object[] values)
{
if (values is null || values.Length == 0)
return false;
else if (values.Length == 1)
return true;
else if (values.Lenght == 2)
if (!compareTypes)
return values[0] == values[1];
else
return values[0].GetType() == values[1].GetType();
else
{
for(int i = 0; i < values.Lenght - 1; i++)
if(!Compare(compareTypes, values[i], values[i+1]))
return false;
return true;
}
}
Very simple.
Related
I've been trying to implement minimax algorithm in my C# chess engine for a week now and it makes legal moves but not meaningful moves. I cannot find the error, hopefully someone can spot it. I have tried to isolate the problem by testing each method and they all seem to work correctly except minimax.
public enum Piece
{
Empty, Pawn_W, Pawn_B, Knight_W, Knight_B,
Bishop_W, Bishop_B, Rook_W, Rook_B,
Queen_W, Queen_B, King_W, King_B
}
public bool IsPieceWhite(Piece piece)
{
if (piece == Piece.Pawn_W || piece == Piece.Knight_W ||
piece == Piece.Bishop_W || piece == Piece.Rook_W ||
piece == Piece.Queen_W || piece == Piece.King_W)
return true;
else return false;
}
public bool IsPieceBlack(Piece piece)
{
if (piece == Piece.Pawn_B || piece == Piece.Knight_B ||
piece == Piece.Bishop_B || piece == Piece.Rook_B ||
piece == Piece.Queen_B || piece == Piece.King_B)
return true;
else return false;
}
public int GetPieceWorth(Piece piece)
{
if (piece == Piece.Pawn_W || piece == Piece.Pawn_B)
return 1;
if (piece == Piece.Knight_W || piece == Piece.Knight_B)
return 3;
if (piece == Piece.Bishop_W || piece == Piece.Bishop_B)
return 3;
if (piece == Piece.Rook_W || piece == Piece.Rook_B)
return 5;
if (piece == Piece.Queen_W || piece == Piece.Queen_B)
return 9;
if (piece == Piece.King_W || piece == Piece.King_B)
return 9999999;
return 0;
}
Piece[,] CurrentBoard = GetStartingBoard();
Piece[,] bestMove;
public int depthB = 3;
public double minimax(Piece[,] board, int depth, bool maximizingPlayer)
{
if (depth == 0)
{
double result = EvaluatePosition(board, maximizingPlayer);
return result;
}
if (maximizingPlayer)
{
double best = Double.MinValue;
double value = Double.MinValue;
foreach (var move in GenerateMoves(board, maximizingPlayer))
{
Piece[,] clonedMove = CloneBoard(move);
value = Math.Max(value, minimax(clonedMove, depth - 1, false));
if (depth == depthB && value >= best)
{
best = value;
bestMove = clonedMove;
}
}
return value;
}
else
{
double best = Double.MaxValue;
double value = Double.MaxValue;
foreach (var move in GenerateMoves(board, maximizingPlayer))
{
Piece[,] clonedMove = CloneBoard(move);
value = Math.Min(value, minimax(clonedMove, depth - 1, true));
if (depth == depthB && value <= best)
{
best = value;
bestMove = clonedMove;
}
}
return value;
}
}
public Piece[,] CloneBoard(Piece[,] boardPos)
{
Piece[,] copy = boardPos.Clone() as Piece[,];
return copy;
}
public double EvaluatePosition(Piece[,] boardPos, bool ForWhite)
{
double eval = 0;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (boardPos[i, j] != Piece.Empty)
{
if (IsPieceWhite(boardPos[i, j]))
{
eval += GetPieceWorth(boardPos[i, j]);
}
else if (IsPieceBlack(boardPos[i, j]))
{
eval -= GetPieceWorth(boardPos[i, j]);
}
}
}
}
if (ForWhite)
return eval;
else
return eval * -1;
}
//a-h,0-7
//Piece[,] board = new Piece[8, 8];
public static Piece[,] GetStartingBoard()
{
Piece[,] board = new Piece[8, 8];
for (int i = 0; i < 8; i++)
{
//initiate pawns
board[1, i] = Piece.Pawn_W;
board[6, i] = Piece.Pawn_B;
}
//white pieces
board[0, 0] = Piece.Rook_W;
board[0, 1] = Piece.Knight_W;
board[0, 2] = Piece.Bishop_W;
board[0, 3] = Piece.Queen_W;
board[0, 4] = Piece.King_W;
board[0, 5] = Piece.Bishop_W;
board[0, 6] = Piece.Knight_W;
board[0, 7] = Piece.Rook_W;
//black pieces
board[7, 0] = Piece.Rook_B;
board[7, 1] = Piece.Knight_B;
board[7, 2] = Piece.Bishop_B;
board[7, 3] = Piece.Queen_B;
board[7, 4] = Piece.King_B;
board[7, 5] = Piece.Bishop_B;
board[7, 6] = Piece.Knight_B;
board[7, 7] = Piece.Rook_B;
//test
//board[1, 4] = Piece.Pawn_B;
//board[6, 2] = Piece.Pawn_W;
return board;
}
I have uploaded a short clip of the engine playing against itself, to show the wierd moves: https://www.youtube.com/watch?v=A0HVgXYSciY
Finally was able to make the minimax function work. Thanks for all the help!
Working method:
public int minimax(Piece[,] board, int depth, bool maximizingPlayer, bool WhiteToPlay)
{
if (depth == 0)
{
int result = EvaluatePosition(board, WhiteToPlay);
return result;
}
var moves = GenerateMoves(board, WhiteToPlay);
if (maximizingPlayer)
{
int value = int.MinValue;
foreach (var move in moves)
{
int minmaxResult = minimax(move, depth - 1, false, !WhiteToPlay);
value = Math.Max(value, minmaxResult);
if (depth == depthB)
{
moveScores.Add(move, minmaxResult);
}
}
return value;
}
else
{
int value = int.MaxValue;
foreach (var move in moves)
{
int minmaxResult = minimax(move, depth - 1, true, !WhiteToPlay);
value = Math.Min(value, minmaxResult);
if (depth == depthB)
{
moveScores.Add(move, minmaxResult);
}
}
return value;
}
}
I have a list of objects with lists of child objects which also have lists of child objects, etc. Here is a simplification with objects A and H:
I would like to print them out in a 2D array, like so:
But I keep getting this:
I'm using recursion for the first time, so tracking which row I'm on for which nested level is difficult. The code I'm using is cluttered with a bunch of carve-outs, so I'm hesitant to post it.
Does anyone have some pseudo-code that could help me fix my alignment issues?
List<int> levelStart = new List<int>();
List<int> levelEnd = new List<int>();
int tempEnding = 0;
public void propertyValues2(Object inv, object[,] dataTest)
{
Type objType = inv.GetType();
PropertyInfo[] properties = inv.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
DisplayNameAttribute DNA = (DisplayNameAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault();
object propValue = property.GetValue(inv, null);
var elems = propValue as System.Collections.IList;
if (exportAll == true || exportColumns.Contains(DNA.DisplayName))
{
if (elems != null && elems.Count != 0)
{
foreach (var item in elems)
{
if (!item.GetType().FullName.StartsWith("System.String"))
{
levelStart.Add(levelStart[levelStart.Count-1]);
propertyValues2(item, dataTest);
levelStart.RemoveAt(levelStart.Count - 1);
}
else if (exportColumns.Contains(DNA.DisplayName) || exportAll == true)
{
int counter = tempEnding;
if (dataTest[tempEnding, columnIDs[DNA.DisplayName]] != null)
{
//dataRow = level[0];
for (int di = tempEnding; dataTest[di, columnIDs[DNA.DisplayName]] != null; di++)
{
tempEnding = di+1;
}
}
dataTest[tempEnding, columnIDs[DNA.DisplayName]] = item;
if (tempEnding > endingRow)
{
endingRow = tempEnding;
}
}
}
tempEnding = levelStart[levelStart.Count-1];
//dataRow = level[0];//level[0]
}
else if (elems != null && elems.Count == 0)
{
int i = 0;
}
else if (propValue != null && propValue.ToString() != "")
{
//dataRow = level[0];//level[0]
//int counter = level[level.Count-1];
if(DNA.DisplayName == "Procedure" || DNA.DisplayName == "Revenue Code")
{
if (columnIDs.Keys.Contains("Procedure") && columnIDs.Keys.Contains("Revenue Code"))
{
for (int di = tempEnding; dataTest[di, columnIDs["Procedure"]] != null || dataTest[di, columnIDs["Revenue Code"]] != null; di++)
{
tempEnding++;
}
}
}
if (dataTest[tempEnding, columnIDs[DNA.DisplayName]] != null)
{
for (int di = tempEnding; dataTest[di, columnIDs[DNA.DisplayName]] != null; di++)
{
tempEnding++;
}
}
dataTest[tempEnding, columnIDs[DNA.DisplayName]] = propValue.ToString();
if (tempEnding > endingRow)
{
endingRow = tempEnding;
}
}
}
else if (elems != null && elems.Count != 0)
{
levelStart.Add(levelStart[levelStart.Count - 1]);
foreach (var item in elems)
{
if (!item.GetType().FullName.StartsWith("System.String"))
{
propertyValues2(item, dataTest);
}
else if (exportColumns.Contains(DNA.DisplayName) || exportAll == true)
{
int counter = levelStart[levelStart.Count - 1];
if (dataTest[counter, columnIDs[DNA.DisplayName]] != null)//level[level.Count - 1]
{
for (int di = levelStart[0]; dataTest[di, columnIDs[DNA.DisplayName]] != null; di++)
{
counter++;//level[level.Count - 1]
}
}
dataTest[counter, columnIDs[DNA.DisplayName]] = item;//level[level.Count - 1]
if (endingRow < counter)
{
endingRow = counter;
}
}
levelStart[levelStart.Count - 1] = endingRow + 1;
}
levelStart.RemoveAt(levelStart.Count - 1);
}
}
foreach (string columnToCopy in columnsToCopy)
{
if (exportColumns.Contains(columnToCopy) || exportAll == true)
{
for (int i = levelStart[0] + 1; i <= endingRow; i++)//level[0]
{
dataTest[i, columnIDs[columnToCopy]] = dataTest[i - 1, columnIDs[columnToCopy]];
}
}
}
}
Array Structure:
Here is the code I worked on yesterday. It seems to work in my test runs, but I will continue testing today. It has too many row changes while printing for me to keep track of, so I'm not completely sure it always prints correctly:
int startInvoice = 1;
List<int> levelStart = new List<int> { 1 };
List<int> levelEnd = new List<int> { 1 };
List<int> maxWithinLevel = new List<int> { 0 };
int depth = 0;
public int propertyValues3(Object inv, object[,] dataTest)
{
//int maxWithinLevel = 0;
PropertyInfo[] properties = inv.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
DisplayNameAttribute DNA = (DisplayNameAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault();
object propValue = property.GetValue(inv, null);
var elems = propValue as System.Collections.IList;
//if its a list
if (elems != null && elems.Count != 0)
{
levelStart.Add(levelEnd[levelEnd.Count - 1]);
levelEnd.Add(levelStart[levelStart.Count - 1]);
foreach (var item in elems)
{
//if its a class
if (!item.GetType().FullName.StartsWith("System.String"))
{
depth++;
levelStart[levelStart.Count-1] = propertyValues3(item, dataTest);
depth--;
if (levelEnd[levelEnd.Count - 1] < levelStart[levelStart.Count - 1])
{
levelEnd[levelEnd.Count - 1] = levelStart[levelStart.Count - 1];
}
}
//if its a string
else
{
if (dataTest[levelEnd[levelEnd.Count - 1], columnIDs[DNA.DisplayName]] != null)
{
for (int i = levelEnd[levelEnd.Count - 1]; dataTest[i, columnIDs[DNA.DisplayName]] != null; i++)
{
levelEnd[levelEnd.Count - 1] = i + 1;
}
}
dataTest[levelEnd[levelEnd.Count - 1], columnIDs[DNA.DisplayName]] = item; //legit
if (levelEnd[levelEnd.Count - 1] > endingRow)//legit
{
endingRow = levelEnd[levelEnd.Count - 1];
}
}
}
levelStart.RemoveAt(levelStart.Count - 1);
//if (!elems[0].GetType().FullName.StartsWith("System.String"))
if(depth>0)
{
maxWithinLevel.Add(levelEnd[levelEnd.Count - 1]);
}
levelEnd.RemoveAt(levelEnd.Count - 1);
}
//if elems is empty
else if (elems != null && elems.Count == 0)
{
int i = 0;
}
//if it's not a list
else if (propValue != null && propValue.ToString() != "")
{
//handle procedure/revcode
if (DNA.DisplayName == "Procedure" || DNA.DisplayName == "Revenue Code")
{
if (columnIDs.Keys.Contains("Procedure") && columnIDs.Keys.Contains("Revenue Code"))
{
for (int i = levelEnd[levelEnd.Count - 1]; dataTest[i, columnIDs["Procedure"]] != null || dataTest[i, columnIDs["Revenue Code"]] != null; i++)
{
levelEnd[levelEnd.Count - 1]++;
}
}
}
if (dataTest[levelEnd[levelEnd.Count - 1], columnIDs[DNA.DisplayName]] != null)
{
for (int i = levelEnd[levelEnd.Count - 1]; dataTest[i, columnIDs[DNA.DisplayName]] != null; i++)//legit
{
levelEnd[levelEnd.Count - 1]++;
}
}
dataTest[levelEnd[levelEnd.Count - 1], columnIDs[DNA.DisplayName]] = propValue.ToString();//level[level.Count - 1]
if (levelEnd[levelEnd.Count - 1] > endingRow)
{
endingRow = levelEnd[levelEnd.Count - 1];
}
}
}
if (levelStart.Count==0 || levelStart.Max() < maxWithinLevel.Max())
{
return maxWithinLevel.Max() + 1;
}
else return levelStart.Max();
}
I am trying to make a string calculator, it works fine with two numbers but I always encounter a problem when evaluating multiple operations:
7*2+4=
Also can you help me with my multiplication and division code. I don't understand why it prints 0 even with just two numbers(7*5)
using System;
using System.Text.RegularExpressions;
namespace Sariling_Calcu
{
class Program
{
private static string exp;
private static int[] i = new int[1000];
private static char[] oper = new char[10];
private static int cntr2;
private static int result;
private static int pluscount;
private static int subcount;
private static int mulcount;
private static int divcount;
static void getNum()
{
string[] strNum = (Regex.Split(exp, #"\D+"));
for (int cntr = 0; cntr < exp.Length; cntr++)
{
foreach (string item in strNum)
{
if (!string.IsNullOrEmpty(item))
{
i[cntr] = int.Parse(item);
cntr += 1;
}
}
}
}
static void counter()
{
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] == '+')
{
pluscount++;
}
else if (exp[cntr] == '-')
{
subcount++;
}
else if (exp[cntr] == '*')
{
mulcount++;
}
else if (exp[cntr] == '/')
{
divcount--;
}
}
}
static void oprtr()
{
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] != '1'
&& exp[cntr] != '2'
&& exp[cntr] != '3'
&& exp[cntr] != '4'
&& exp[cntr] != '5'
&& exp[cntr] != '6'
&& exp[cntr] != '7'
&& exp[cntr] != '8'
&& exp[cntr] != '9')
{
if (exp[cntr] == '+')
{
result += i[cntr2];
cntr2 += 1;
pluscount--;
if (pluscount == 0 && subcount == 0 && mulcount==0 && divcount==0)
{
cntr2 += 3;
result += i[cntr2];
}
}
else if (exp[cntr] == '-')
{
result -= i[cntr2];
cntr2 += 1;
subcount--;
result = -result;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result -= i[cntr2];
}
}
else if (exp[cntr] == '*')
{
if (result == 0)
{
result += 1;
}
result *= i[cntr2];
cntr2 += 1;
mulcount--;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result *= i[cntr2];
}
}
else if (exp[cntr] == '/')
{
if (result == 0)
{
result += 1;
}
result /= i[cntr2];
cntr2 += 1;
divcount--;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result /= i[cntr2];
}
}
}
}
}
static void Main(string[] args)
{
Console.Write("Expression: ");
exp = Console.ReadLine();
counter();
getNum();
oprtr();
Console.Write("Answer: \n" + result);
Console.ReadLine();
}
}
}
you could use LINQ to reduce your code to a few lines but looks like its a school assignment where you would have to go with Arrays and loops.
I have tried to refine your code a bit and did a few fixes, change getNum(), counter() and oprtr() methods as below and let me know if it works, then I would add some comments in the code to explain changes I made.
static void getNum()
{
string[] strNum = (Regex.Split(exp, #"\D+"));
for (int cntr = 0; cntr < strNum.Length; cntr++)
{
if (!string.IsNullOrEmpty(strNum[cntr]))
{
i[cntr] = int.Parse(strNum[cntr]);
}
}
}
static void counter()
{
cntr2 = 0;
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] == '+')
{
oper[cntr2] = '+';
cntr2++;
}
else if (exp[cntr] == '-')
{
oper[cntr2] = '-';
cntr2++;
}
else if (exp[cntr] == '*')
{
oper[cntr2] = '*';
cntr2++;
}
else if (exp[cntr] == '/')
{
oper[cntr2] = '/';
cntr2++;
}
}
}
static void oprtr()
{
result = i[0];
cntr2 = 1;
for (int cntr = 0; cntr < oper.Length; cntr++)
{
if (oper[cntr] == '+')
{
result += i[cntr2];
}
else if (oper[cntr] == '-')
{
result -= i[cntr2];
}
else if (oper[cntr] == '*')
{
result *= i[cntr2];
}
else if (oper[cntr] == '/')
{
if (i[cntr2] == 0)
{
throw new DivideByZeroException();
}
result /= i[cntr2];
}
cntr2 += 1;
}
}
Currently, I am doing a log analyzer for my personal project.
My issue here is that I am new to c# and I have an performance issue with my tool.
Everytime the device(iOS) is interacted, I get an output syslog from a library and it comes in to the output handler.
public void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine, iosSyslogger form, string uuid)
{
string currentPath = System.Environment.CurrentDirectory;
bool exit = false;
if (exit == true) return;
try
{
form.BeginInvoke(new Action(() =>
{
form.insertLogText = outLine.Data;
}));
using (System.IO.StreamWriter file = new System.IO.StreamWriter(currentPath + #"\syslog" + uuid + ".txt", true))
{
file.WriteLine(outLine.Data);
}
}
catch
{
return ;
}
//*Most of the logic for outputing the log should be dealt from this output Handler
}
Then, I write the outline.Data to Data grid view. My concern is that I need to be able to search and filter through data gridview.
Curently I am using visibility = false for search filtering ( if the row does not match the given filter specification I set the row to visibility =false)
This requires the program to traverse the entire datagridview to check whether the condition is met.
Will there be any better way to filter and search within ?
(When I have thousands of lines of row, it takes at least 20 seconds to process it)
Below is the code for filtering, and searching through the results function.
private void searchResult(string term)
{
if (term != null)
{
int i = 0;
while (i < dataGridView1.Rows.Count - 1)
{
if (dataGridView1.Rows[i].Cells[3] == null)
{
i++;
continue;
}
if (dataGridView1.Rows[i].Visible == false)
{
i++;
continue;
}
else if (dataGridView1.Rows[i].Cells[2].Value.ToString().Contains(term) || dataGridView1.Rows[i].Cells[3].Value.ToString().Contains(term) || dataGridView1.Rows[i].Cells[4].Value.ToString().Contains(term))
{
string multirow = dataGridView1.Rows[i].Cells[5].Value.ToString();
int count = Convert.ToInt32(multirow);
if (count > 0)
{
int z = 0;
for (z = 0; z <= count; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
i = i + z;
}
else
{
dataGridView1.Rows[i].Visible = true;
i++;
}
}
else
{
dataGridView1.Rows[i].Visible = false;
i++;
}
}
}
}
public filteringThelist(){
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Visible = false;
int count1,count2,count3=0;
count1 = 1;
count2 = 1;
count3 = 1;
int z = 0;
foreach (KeyValuePair<string, string> entry in totalSelected)
{
if (entry.Value == "devicename" && dataGridView1.Rows[i].Cells[1].Value != null)
{
if (dataGridView1.Rows[i].Cells[1].Value.ToString().Trim().Equals(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
}
else if (devicename.CheckedItems.Count > 1&&count1!= devicename.CheckedItems.Count)
{
count1++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
else if (entry.Value == "process" && dataGridView1.Rows[i].Cells[2].Value != null)
{
if (dataGridView1.Rows[i].Cells[2].Value.ToString().Trim().Equals(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
}
else if (processlistname.CheckedItems.Count > 1 && count2 != processlistname.CheckedItems.Count)
{
count2++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
else if (entry.Value == "loglevel" && dataGridView1.Rows[i].Cells[3].Value != null)
{
if (dataGridView1.Rows[i].Cells[3].Value.ToString().Trim().Contains(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
continue;
}
else if (loglevelCheckBox.CheckedItems.Count > 1 && count3 != loglevelCheckBox.CheckedItems.Count)
{
count3++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
// do something with entry.Value or entry.Key
}
string multirow = dataGridView1.Rows[i].Cells[5].Value.ToString();
int count = Convert.ToInt32(multirow);
if (count > 0&& dataGridView1.Rows[i].Visible==false)
{
for (int k = 0; k <= count; k++)
{
dataGridView1.Rows[i + k].Visible = false;
}
}
i = i + z;
}
The performance problem is because your DataGridView is redrawing at each modification.
Don't fill the DataGridView directly from your Data. Rather create a DataTable and bind it to DataGridView with a BindingSource.
Then use the "Filter" property of the binding source to view extracts of dataTable in the DataGridView. The "Filter" property is a string whose content is similar to that of a WHERE SQL clause.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Relatively new to programming but I can't work out why my If statement is unreachable. Also what would be the best way to return the calculation so I can send it back?
while (Reader.Read()) {
if (Reader.NodeType == XmlNodeType.Element)
{
if (Reader.Name == "Amount")
{
if ("Amount" == "Gold" || value > 4999)
{
credit = 300;
DiscountPercent = .20f;
}
else if ("Amount" == "Silver" || value > 4999)
{
DiscountPercent = .15f;
}
else if ("Amount" == "Regular")
{
credit = 200;
}
}
else if (Reader.Name == "Member")
{
if ("Member" == "Gold" || value > 4999)
{
credit = 300;
DiscountPercent = .20f;
}
else if ("Member" == "Silver" || value > 4999)
{
DiscountPercent = .15f;
}
else if ("Member" == "Regular")
{
credit = 200;
}
}
}
}
}
Could it be because I'm not including a break statement?
"Amount" == "Gold" will never evaluate to true, because the strings are different. Same goes for other string comparisons. Compiler reduces this false out of the ||, so it "sees" the following:
if (value > 4999) {
credit = 300;
DiscountPercent = .20f;
} else if (value > 4999) {
DiscountPercent = .15f;
} else if (false) {
credit = 200;
}
The compiler reasonably concludes that the middle and the bottom ifs are unreachable.
To fix this code, read the value, and use it in your comparisons:
if (Reader.Name == "Amount") {
var amount = Reader.Value;
if (amount == "Gold" || value > 4999) {
credit = 300;
DiscountPercent = .20f;
} else if (amount == "Silver" || value > 4999) {
DiscountPercent = .15f;
} else if (amount == "Regular") {
credit = 200;
}
}
I've re-written your code to make it compile:
static void Main(string[] args)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader Reader = XmlReader.Create("items.xml", settings);
int value = 500;
int credit = 0;
var DiscountPercent = 0.1f;
while (Reader.Read())
{
if (Reader.NodeType == XmlNodeType.Element)
{
if (Reader.Name == "Amount")
{
if ("Amount" == "Gold" || value > 4999)
{
credit = 300;
DiscountPercent = .20f;
}
else if ("Amount" == "Silver" || value > 4999)
{
DiscountPercent = .15f;
}
else if ("Amount" == "Regular")
{
credit = 200; //unreachable code detected
}
Reader.Read();
}
else if (Reader.Name == "Member")
{
if ("Member" == "Gold" || value > 4999)
{
credit = 300;
DiscountPercent = .20f;
}
else if ("Member" == "Silver" || value > 4999)
{
DiscountPercent = .15f;
}
else if ("Member" == "Regular")
{
credit = 200; //unreachable code detected
}
Reader.Read();
}
}
}
}
I've added some suggestions to help you figure out what's going on...
static void Main(string[] args)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create("items.xml", settings);
int value = 500;
int credit = 0;
var discountPercent = 0.1f; //generally people use lower case for variables
var amountType = "Gold"; //added this variable to replace constant
var memberType = "Gold"; //added this variable to replace constant
while (reader.Read()) //generally people use lower case for variables "reader.Read()"
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "Amount")
{
//two constant but different strings will never equal each other...
//, just like the integer 1 will never equal 2
if ("Amount" == amountType || value > 4999)
{
credit = 300;
discountPercent = .20f;
}
else if ("Amount" == amountType || value > 4999)
{
discountPercent = .15f;
}
else if ("Amount" == amountType)
{
credit = 200; //no error, code is now reachable
}
reader.Read();
}
else if (reader.Name == "Member")
{
if ("Member" == memberType || value > 4999)
{
credit = 300;
discountPercent = .20f;
}
else if ("Member" == memberType || value > 4999)
{
discountPercent = .15f;
}
else if ("Member" == memberType)
{
credit = 200; //no error, code is now reachable
}
reader.Read();
}
}
}
}