简体   繁体   中英

Foreach loop help c#

I'm currently trying to pull data from a database using a variable and then pass it into a foreach loop to determine if a button should be shown based on a value.

SO far I have this:

var Inter = from x in db.DT_Interviews where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID select x;

foreach(var c in Inter)
{
    if (c.InterviewDone == true)
        BTI.Visible = false;
    else
        BTI.Visible = true;
 }

However I am unable to get the loop to work! Can someone show me or explain what I am doing wrong here?

If you're trying to show BTI if any interview is associated to the viewstate client ID and having the InterviewDone flag = true, you can use:

int clientID = int.Parse(ViewState["ClientID"].ToString());
BTI.Visible = db.DT_Interviews.Any(x => x.ClientID == clientID && x.InterviewDone);

But why do you need to check that the ClientID is same as the one in the view state AND CID?

Your code is very strange at several places:

var Inter = 
  from x in db.DT_Interviews 
  where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID 
  select x; 

Are you sure that your query returns any result? what is the value of CID?

  foreach(var c in Inter) 
  { 
     if (c.InterviewDone == true) 
            BTI.Visible = false; 
         else 
            BTI.Visible = true; 
      } 
  }

I am not sure that you are doing here? The BTI will be visible or not depeding upon the last element in your query. So, why to loop over the whole content then?

Firstly, why have you got a foreach to set 2 scenarios only ie set the visibility of some object to false or true. Imagine if your Inter has got 5 bool values, then the visibility of your object is dependant upon the last value in the Inter because it will continue to loop until it hits the last value. Isn't it. Try this code:

Here, I am getting a bool value in Inter as soon as it finds the first value.

var Inter = (from x in db.DT_Interviews
             where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID
             select x.InterviewDone).FirstOrDefault();

if(Inter)
{
    BTI.Visible = false;
}      
else
{
    BTI.Visible = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM