How to add condition to loop - c#

I wanna check a value in array and if it exist return the value else return the message and read another value from array. add
else
{
MessageBox.Show("This Item ID Does Not Exist");
}
but the problem is when the the value is not in array, it want to show the message for 1258038 times.
how can I check the value (input) and if it exists, i can continue and if it does not exist in array , it returns back and read another value (input can be several values that must read one by one)
for (int cun = 0; cun < ItemIdNumber.Length; cun++)
{
int Item_Id = Convert.ToInt32(ItemIdNumber[cun]);
for (int yyu = 0; yyu <= 1258038; yyu++)
{
int weer = c[yyu];
if (weer == Item_Id)
{
itemseq = yyu;
}
else
{
MessageBox.Show("This Item ID Does Not Exist");
}
}
float[] i_ff = b[itemseq];
for (int ii = 0; ii < i_ff.Length; ii++)
{
.......

Use break to leave the loop early. You'll also need to change your logic a bit so you're not displaying a message in every iteration. This is just one possibility:
int? itemseq = null;
for (...) // outer loop
{
...
for (...) // inner loop
{
if (weer == Item_Id)
{
itemseq = yyu;
break;
}
}
if (!itemseq.HasValue)
MessageBox.Show("This Item ID Does Not Exist");
...
}
I think with a little bit of thought, you could make this more readable.
You've got two collections to search - ItemIdNumber and c.
You're looking for the first value in ItemIdNumber that matches an item in the first 1258038 values of c.
Something like this LINQ statement maybe, although I'm not exactly sure what type your collections are. And I'm writing this free-hand, so it might not compile as-is. Should give you something to work with though.
var id = (from id in ItemIdNumber
join cid in c.Take(1258038) on Convert.ToInt32(id) equals cid
select cid).FirstOrDefault();
if (!id.HasValue)
MessageBox.Show("This Item ID Does Not Exist");

for (int cun = 0; cun < ItemIdNumber.Length; cun++) {
...
boolean found = false;
for (int yyu = 0; yyu <= 1258038; yyu++) {
int weer = c[yyu];
if (weer == Item_Id)
{
itemseq = yyu;
found = true;
break;
}
}
if(!found) {
MessageBox.Show("This Item ID Does Not Exist");
}
...
}

Related

Trying to change an element in a Collection

I'm trying to modify this code. I need to check for a value in a specific element of FilteredCheckObservable and if true, change the value of another part of that element.
Basically something like
if (FilteredCheckObservable items.Lang = 'ENG')
{items.check = newcheckname;}
Then this will update the sourceGroups Collection.
if (string.IsNullOrEmpty(departmentLine.LineID) || string.IsNullOrEmpty(departmentLine.LineName))
continue;
bool discovered = false;
foreach (var group in sourceGroups)
{
if (!group.Key.Line.IsEqual(departmentLine))
continue;
group.Key.IsDiscovered = true;
discovered = true;
group.Key.ScheduleStatusCount = group.CountGroupItem;
break;
}
if (discovered == false)
{
var _ScheduleItemObservable = new ScheduleItemObservable(departmentLine, MainViewViewModel, Shift.ToString());
var item = new Grouping<ScheduleItemObservable, FilteredCheckObservable>(_ScheduleItemObservable);
if (IsShiftValid)
{
item.Key.Shift = Shift.ToString();
item.Key.IsHistoryEnabled = true;
}
sourceGroups.Add(item);
}
for (int index = 0; index < sourceGroups.Count; index++)
{
if (sourceGroups[index].Key.IsDiscovered == true)
{
foreach (var group in sourceGroups)
{
foreach (FilteredCheckObservable items in group)
{
if (items.Lang_ID == LanguageService.Instance.LanguageType.ToString())
{
sourceGroups.Clear();
sourceGroups.Add(item);
}
}
}
}
}
Welcome Travis,
I would wager the guilty culprit is your foreach loop.
https://stackoverflow.com/a/759985/3403999
You aren't allowed to modify a collection inside of a foreach loop.
I don't know if your collection has an indexer, but if it does, you can convert to a for loop:
for (int i = 0; i < sourceGroups.Count; i++)
{
var group = sourceGroups[i];
// The rest of your code.
I could be wrong. You do say you are trying to modify some existing code. Is it some code that is online? Maybe you could link to it to provide a full context.
Based on your new snippet, you need two for loops:
for (int index = 0; index < sourceGroups.Count; index++)
{
if (sourceGroups[index].Key.IsDiscovered == true)
{
//foreach (var group in sourceGroups)
for (int j = 0; j < sourceGroups.Count; j++)
{
var group = sourceGroups[j];
foreach (FilteredCheckObservable items in group)
{
if (items.Lang_ID == LanguageService.Instance.LanguageType.ToString())
{
sourceGroups.Clear();
sourceGroups.Add(item);
}
}
}
}
}
^ Although that might still be a bad loop. Primarily because you have sourceGroups.Clear();.
What you might be better off doing is creating an internal collection called say 'results'. Do your loop looking for your conditions, and if they meet, add that item to the results collection.
Once your loops terminate, then call sourceGroups.Clear(), and then sourceGroups.AddRange(results). If sourceGroups doesn't have an AddRange, then one final loop of:
foreach (var group in results) { sourceGroups.Add(group); }

compare the items in list in c#

i want to compare the selecteditem of combobox with the selecteditem of other combobox
for this i have registered all the comboboxes in a list and named it "panel1kilist"
now the problem i am facing is that when there are same items in two comboboxes first the messagebox shows "no mattch found" and then it shows "match found" actually it goes to the else statement of inner loop first and then to if statement kindly help
private void button1_Click(object sender, EventArgs e)
{
bool check = false;
bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
{
for (int i = 1; i < panel1kilist.Count; i++)
{
for (int j = i + 1; j < panel1kilist.Count; j++)
{
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
}
}
}
catch (System.NullReferenceException)
{
MessageBox.Show("please fill all the boxes first");
}
}
Your question is not really clear but I still try to give you some help. As mentioned in the comments there are several small issues in your code:
1. The outter for-loop
for (int i = 1; i < panel1kilist.Count; i++)
You define i = 1, which means you skip the very first item in your panel1kilist because lists and arrays start at index 0
2. Use of your bool variables
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
You define your bool variables before starting your for-loops. So whenever you set your variables check and check1 to true, the if conditions check == false and check1 == false will never return true anymore. So you will never get any message except the very first "Match found" and "no match found".
3. My proposed solution
Make use of the foreach-loop and break the loops once you found a match, after the loops just show the message. Code:
var matchFound = false;
foreach (var combobox in panel1kilist)
{
foreach (var comboboxToMatch in panel1kilist.Skip(1))
{
if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
{
matchFound = true;
// Stops the inner loop in case of a match
break;
}
}
// Stops the outer loop in case of a match
if(matchFound)
{
break;
}
}
if(matchFound)
{
MessageBox.Show("match found");
}

how to check error conditions c#

I have group of conditions like
foreach
{
Condition a
condition b
}
So I am validating the values based on conditions.I am facing the problem: for example I have list of items like {1,2,3,4}. So I have a condition like if item 1 is fail then item 2,3,4 should be fail.
if item 2 is fail then item 3,4 should be fail and so on.
I am trying in below code.
foreach (SagaData item in lstPrm)
{
PriceDetail prevPrice = null;
PriceDetail currentPrice = null;
PriceDetail nextPrice = null;
bool bHasError = false;
int iPriceMasterId = 0;
int iPriceTypeId = 0;
string sMprCurrencyType = null;
string sPublisherCurrencyType = null;
int? iExpirationCalendarId = 0;
string sPRMMessage = string.Empty;
//a) If Change Indicator = C or A and Price = 0.00: Cannot change price value to zero.
if ((item.ChangeIndicator == 'C' || item.ChangeIndicator == 'A') && item.PostingPrice == 0)
{
bHasError = true;
sPRMMessage = "FAILURECannot change price value to zero";
}
//b) If Change Indicator = D and Price > 0.00: Invalid deactivation.
if ((item.ChangeIndicator == 'D') && (item.PostingPrice > 0) && (!bHasError))
{
bHasError = true;
sPRMMessage = "FAILUREInvalid deactivation";
}
so i have if condition a fail for item 1 then how should i keep maintain the error for next iteration.
Thanks for the help. if you want more info plz let me know.
You can go through your Collection with a simple for loop and use an ErrorArray:
bool[] bHasError = new bool[lstPrm.Count];
for (int i = 0; i < lstPrm.Count; i++)
{
...
bHasError[i] = true;
...
}
or you can define bHasError BEFORE the foreach if one error is enough for you to consider.

How to check if an element is already exists in DataGrid

I made a code that check if in my DataGrid a particular element is already exists.
If the elements is already added in the DataGrid the code show a pop-up to the user. This is the code:
if (grid.Items.Count > 0)
{
for (int i = 0; i < grid.Items.Count; i++)
{
if (((Teams.Club_Information)grid.Items[i]).name == reader["name"].ToString())
{
MessageBox.Show("La squadra è già stata inserita!");
}
else
{
MainWindow.AppWindow.Squadre_DataGrid.Items.Add(new Teams.Club_Information
{
name = reader["name"].ToString(),
code = reader["code"].ToString(),
shortName = reader["shortName"].ToString(),
squadMarketValue = reader["SquadMarketValue"].ToString()
});
}
}
}
else
{
MainWindow.AppWindow.Squadre_DataGrid.Items.Add(new Teams.Club_Information
{
name = reader["name"].ToString(),
code = reader["code"].ToString(),
shortName = reader["shortName"].ToString(),
squadMarketValue = reader["SquadMarketValue"].ToString()
});
}
In the first condition I check if there's row in the DataGrid, if the condition is true then I iterate through the element of DataGrid.
Now the problem is that I'm compare a grid item with the attribute "name" of the reader. reader is the variable the read of the element of a query result (sqlite).
There's another way to check in the column name of my DataGrid if the element is already added?
Your items are of type "Teams.Club_Information", but you are comparing them to reader["name"] which is a string. Unless you have written an Equals method which will compare Club_Information.name to a string, the comparison will always fail.
Try instead:
if (((Teams.Club_Information)grid.Items[i]).name == reader["name"])
You can do something like this
if(grid.Items.Contains(reader["name"]))
{
MessageBox.Show("team already added");
}
else
{
MainWindow.AppWindow.Squadre_DataGrid.Items.Add(new Teams.Club_Information
{
name = reader["name"].ToString(),
code = reader["code"].ToString(),
shortName = reader["shortName"].ToString(),
squadMarketValue = reader["SquadMarketValue"].ToString()
});
}
var name = reader["name"];
var isNamePresent = grid.Items
.Cast<Teams.Club_Information>()
.Any(item => item.name == name);
if (isNamePresent) ... else ...

Messagebox issue with If

I'm having weird behavior with my messagebox
here is the code:
private async void rate_Tap(object sender, System.Windows.Input.GestureEventArgs e) {
string id = (string)((Image)sender).Tag;
ignoreSelectionChanged = true;
MobileServiceCollection<rating, rating> items;
IMobileServiceTable<rating> itemTable = App.MobileService.GetTable<rating>();
items = await itemTable
.Where(Table => Table.userid == userId)
.ToCollectionAsync();
if (id != null) {
for (int i = 0; i < items.Count; i++) {
if (items[i].itemid == id) {
MessageBox.Show("You already giving your rating.");
i = items.Count;
return;
}
else {
RadMessageBox.Show(
new string[] { "very accurate", "not accurate" },
"Acurate?",
"Is this information accurate?", closedHandler: (args) => {
int buttonIndex = args.ButtonIndex;
if (buttonIndex == 0) {
clearListBox();
ratingPlus(id);
saveRating(id);
mvm.LoadDetailData();
}
if (buttonIndex == 1) {
clearListBox();
ratingMinus(id);
saveRating(id);
mvm.LoadDetailData();
}
}
);
}
}
}
}
What my code above dord is I trigger rate_Tap() from my listbox that already contains image, and each time I tap it , it's supposed to check with my windows azure server and check if there is an itemid that equals id. Then I will show messagebox saying I already rated it and if there isn't any itemid that equals id then it will execute radmessagebox.
But it's not working that way: when it checks there is an itemid that's equal to id, it shows the messagebox and after that it show the radmessagebox.
Where did I go wrong?
Your "else" block contains the code that you want to execute after you've checked all items - not on each item.
I think you want:
if (items.Any(item => item.itemid == id))
{
MessageBox.Show("You already giving your rating.");
return;
}
RadMessageBox.Show(...);
// etc
Ideally, don't fetch all the previous ratings - change your query so that it includes the ID of the item you're trying to rate. After all, you only want to know whether or not you've already rated it - the rest of the information is pointless, so why fetch it all?

Categories