12 Replies - 2162 Views - Last Post: 21 October 2010 - 02:16 PM Rate Topic: -----

#1 wuu   User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 86
  • Joined: 16-March 09

How does foreach work in this case?

Posted 20 October 2010 - 11:10 AM

Ive got the following method:
        private void UrediLabele(GroupBox G, List<string> Lst)
        {
            int i = 0;
            foreach (Label l in G.Controls.OfType<Label>())
            {
                if ((string)l.Tag == "Predpona")
                {
                    int st_del;
                    st_del = Convert.ToInt32(Lst[i][Lst[i].Length - 1]);
                    st_del -= 0x30;
                    if (st_del == 0)
                    {
                        l.Text = "Wh";                     
                    }
                    else if (st_del == 1)
                    {
                        l.Text = "kWh";                       
                    }
                    else if (st_del == 2)
                    {
                        l.Text = "MWh";
                    }
                    else if (st_del == 3)
                    {
                        l.Text = "GWh";
                    }
                    i++;
                }
            }
        }


Method changes label text property to new value based on the st_del variable value. Now my question is how do I know in which sequence those labels are going to be changed? The sequence is centrally not changed based on their label properties, which are named from label1 to label7. Now how can I make foreach from label1 to label7 in serial sequence not like label1, label3, label4, label7,

Is This A Good Question/Topic? 0
  • +

Replies To: How does foreach work in this case?

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 11:29 AM

Quote

Now my question is how do I know in which sequence those labels are going to be changed?

Groupbox.Controls will contain all the controls that were added to the groupbox IN THE ORDER THEY WERE ADDED.
This is the order your ForEach loop will receive them in, from the GroupBox.


Quote

Now how can I make foreach from label1 to label7 in serial sequence not like label1, label3, label4, label7,


Get the list of labels from GroupBox.controls.
Alphabetize them into a new List<Labels>
Then ForEach using the alphabetized List<>
Was This Post Helpful? 1
  • +
  • -

#3 Robin19   User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 11:46 AM

The first option tlhIn'toq mentioned is to change the order they were added. In the <Form1>.Designer.cs code (in the solution explorer expand the <Form1> to find it), find the following code in the InitializeComponent() function.
this.Controls.Add(this.label1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label5);
this.Controls.Add(this.label2);
this.Controls.Add(this.label6);
this.Controls.Add(this.label4);

Change the order to the order you want the controls to found. Be wary, forgetting to add a control will mean it will never appear on your form.

This post has been edited by Robin19: 20 October 2010 - 11:47 AM

Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 11:55 AM

View PostRobin19, on 20 October 2010 - 10:46 AM, said:

The first option tlhIn'toq mentioned is to change the order they were added. In the <Form1>.Designer.cs code (in the solution explorer expand the <Form1> to find it), find the following code in the InitializeComponent() function.
this.Controls.Add(this.label1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label5);
this.Controls.Add(this.label2);
this.Controls.Add(this.label6);
this.Controls.Add(this.label4);

Change the order to the order you want the controls to found. Be wary, forgetting to add a control will mean it will never appear on your form.


If you created your label controls through code in your form's .cs file, then changing the order of adding is not a big deal, since you were already doing this.

BUT - If you created your label controls by dragging from the toolbox all of the code for creating your labels is in the form1.designer.cs file. As it says right in the comments of this file: Don't modify this file as it is automatically generated by Visual Studio. Yes, you can modify it, but if you goof then strange things happen. Visual Studio may re-write this file as it sees fit and all your changes can just *go away* unexpectedly.

I personally feel that your code is more robust if it doesn't care what order the controls were added. It should be smart enough to compensate for controls being added, removed and so on and still work. For the need you mentioned (label1, label2 etc.) simple alphabetization works well. Keep in mind that you might want to use 2 or even 3 digit label names: label001, label002. That way you are all set if you add more than 99 labels.

Of course if you make properties then you can just put in a PropertyGrid on your form. THis would allow you to show and even change the values without being responsible for making and synchronizing a ton of labels.
Was This Post Helpful? 2
  • +
  • -

#5 Ionut   User is offline

  • D.I.C Lover
  • member icon

Reputation: 386
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 12:06 PM

Another way to access your labels in order is:
int iCount = 1;

while (iCount <= 7) //or whatever count you have.  
{
    string s = string.Concat("label", iCount.ToString());
    Label lbl = (Label)Controls[s];
    if (lbl != null)
    {
        lbl.Text = string.Concat("changed label " + iCount.ToString());
        iCount++;
    }
}



Probably it is not the best code written, but you can get an idea.

Ionut
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 12:17 PM

View PostIonut, on 20 October 2010 - 11:06 AM, said:

Another way to access your labels in order is:
int iCount = 1;

while (iCount <= 7) //or whatever count you have.  
{
    string s = string.Concat("label", iCount.ToString());
    Label lbl = (Label)Controls[s];
    if (lbl != null)
    {
        lbl.Text = string.Concat("changed label " + iCount.ToString());
        iCount++;
    }
}



Probably it is not the best code written, but you can get an idea.

Ionut


Have you actually tried this? I've never tried sending a string as the index of a collection like that. Usually you send an int to specify which element of array. Have you confirmed this actually searches the array for the item with the specified name?
Was This Post Helpful? 0
  • +
  • -

#7 Ionut   User is offline

  • D.I.C Lover
  • member icon

Reputation: 386
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 12:24 PM

Quote

Have you actually tried this?


I had tested the code before I posted and it worked even if visual studio suggested that Controls expects an int as index.

Quote

Usually you send an int to specify which element of array. Have you confirmed this actually searches the array for the item with the specified name?

Usually, I do the same, but, in some cases(I cann't get any other example on my mind right now), works this way as well.
Was This Post Helpful? 0
  • +
  • -

#8 wuu   User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 86
  • Joined: 16-March 09

Re: How does foreach work in this case?

Posted 20 October 2010 - 01:44 PM

View PosttlhIn, on 20 October 2010 - 10:29 AM, said:

Quote

Now my question is how do I know in which sequence those labels are going to be changed?

Groupbox.Controls will contain all the controls that were added to the groupbox IN THE ORDER THEY WERE ADDED.
This is the order your ForEach loop will receive them in, from the GroupBox.


Quote

Now how can I make foreach from label1 to label7 in serial sequence not like label1, label3, label4, label7,


Get the list of labels from GroupBox.controls.
Alphabetize them into a new List<Labels>
Then ForEach using the alphabetized List<>


I like this methode the most. Now the only problem is I don't know how to sort labels by name in a list?
I think this is the right way to get them in list. I guess using LabelLst.Sort() would be to easy :)

            List<Label> LabelLst = new List<Label>();

            foreach (Label l in G.Controls.OfType<Label>())
            {
                if ((string)l.Tag == "Predpona")
                {
                    LabelLst.Add(l);
                }
            }


Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How does foreach work in this case?

Posted 20 October 2010 - 01:53 PM

Quote

Now the only problem is I don't know how to sort labels by name in a list?

None of us are born knowing how.
Have you done any research (read "google") for how to sort a list in C#?
Was This Post Helpful? 0
  • +
  • -

#10 wuu   User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 86
  • Joined: 16-March 09

Re: How does foreach work in this case?

Posted 21 October 2010 - 01:56 PM

View PosttlhIn, on 20 October 2010 - 12:53 PM, said:

Quote

Now the only problem is I don't know how to sort labels by name in a list?

None of us are born knowing how.
Have you done any research (read "google") for how to sort a list in C#?


I had done some google research, and find some example how this is handled, although I dont understand everything the code works. Can someone explain me why there are used { } and what do they mean?

people.Sort(delegate(Person p1, Person p2) { return p1.name.CompareTo(p2.name); });



What kind of a function does delegate have here?
Was This Post Helpful? 0
  • +
  • -

#11 AdamSpeight2008   User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: How does foreach work in this case?

Posted 21 October 2010 - 02:13 PM

It is Function take takes two persons and returns a integer.
Return values are;-
<0, if a is before b
=0, if a is equal to b
>0, if a is after b.

See Custom Sorting Tutorial

Also have a look at Lambdas.

people.Sort((Person a,Preson B)/>=> a.name.ComparedTo(B)/>);


Edit

For Each use the ICollection Interface for iteration.

Linq uses the IEnumerable Interface which is why you can't do.

Dim xs As Enumberable.Range(0,100)
For Each x In xs Where x Mod 2=0

This post has been edited by AdamSpeight2008: 21 October 2010 - 02:18 PM

Was This Post Helpful? 0
  • +
  • -

#12 Robin19   User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: How does foreach work in this case?

Posted 21 October 2010 - 02:15 PM

That basically means you are calling the function delegate(Person, Person). You don't plan on using the function outside of this one line. So instead of writing the function by itself, you write it inline. The .Sort method wants a way to compare the objects.
Was This Post Helpful? 0
  • +
  • -

#13 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: How does foreach work in this case?

Posted 21 October 2010 - 02:16 PM

A delegate is an anonymous function.

Lines 3, 4, and 5 in the following code are functionally equivalent.

private static void DoSort(List<Person> people)
{
    people.Sort(DoSort);
    people.Sort(delegate(Person p1, Person p2) { return p1.Name.CompareTo(p2.Name); });
    people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name));
}

private static int DoSort(Person p1, Person p2)
{
    return p1.Name.CompareTo(p2.Name);
}


The first just uses a reference to the proper function.

The second creates an anonymous function on the spot with the proper signature.

The third does the same, except with implicitly typed parameters, and an implicit return. (It's called a Lambda.)

I wrote a tutorial on these, by the way.
http://www.dreaminco...-are-they-used/

This post has been edited by insertAlias: 21 October 2010 - 02:16 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1