Question

I'm currently having a bit of a nightmare with a foreach loop. In a nutshell, what I am trying to do is split a string and then filter this data based on the string. I then need to bind the said data to a control of filter it further down the line. So far, I have the following code

 if (Session["Contract"] != null)
        {
            string[] contract = Session["Contract"].ToString().Split(',');
            foreach (string i in contract)
            {
                if (i.ToString() != "")
                {
                  data = data.Where(x => x.Term.Trim().ToUpper().Contains(i.ToString().Trim().ToUpper()));
                }
            }
        }

        LV_Jobs.DataSource = data;
        LV_Jobs.DataBind();

Now when looping through, the filtering works fine, but once you are finished with one item, the data variable is cleared? Obviously I need to pass "data" back out of the foreach loop. Can anyone point me in the direction of how to do this???

Was it helpful?

Solution

You are resetting data every time the loop iterates. Try this (depending on what data is)

        var filteredData = new List<string>();
        if (Session["Contract"] != null)
        {
            filteredData = Session["Contract"].ToString().Split(',').Join(
                                data, 
                               i => i.ToString().Trim().ToUpper(), 
                               x => x.Term.Trim().ToUpper(),
                               (i, x) => x);
        }

        LV_Jobs.DataSource = filteredData;
        LV_Jobs.DataBind();

OTHER TIPS

Simply collect the needed data out in a list of results or any other data structure declared outside of the for/foreach scope.

Your data variable is not cleared. Instead, in the last iteration of the foreach where i.ToString() != "" your Where() condition is not true. So data becomes an empty list.

You can break out of the foreach when you found what you were looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top