Almacene las variables en la lista/matriz y recorra las posteriores c#

Sorry, I think I was not clear earlier. I am trying to do as O.R.mapper says below- create a list of arbitrary variables and then get their values later in foreach loop.

Moreover, all variables are of string type so I think can come in one list. Thanks.

Is there a way to store variables in a list or array then then loop through them later.

For example: I have three variables in a class c named x,y and Z.

puedo hacer algo como:

public List Max_One = new List {c.x,c.y,c.z}


and then later in the code

          foreach (string var in Max_One)
          {                   
              if ((var < 0) | (var > 1 ))
              {
                // some code here
              }
          }

preguntado el 31 de julio de 12 a las 14:07

I cannot really see the difficulty, is of course acceptable? -

¿Estás tratando de conseguir el valores variables into the list/array, or the referencias variables? -

Your code should pretty much work as is, 'cept in C# var is a keyword (avoid it or prefix it @var) and you have to declare the type if you want them to be strings. -

Put another way, do you want to store the variable values as they are at the time of creation of your list/array, or do you want to select some arbitrary variables and later on get their current values at that time in the foreach loop you're showing? -

Sorry I think I was not clear earlier in what I am trying to do. I am trying to do as O.R.mapper says- create a list of arbitrary variables and then get their values later in foreach loop. Thanks. -

5 Respuestas

Is there a particular reason why you want to tienda the list of variables beforehand? If it is sufficient to reutilizar such a list whenever you need it, I would opt for creating a property that returns an IEnumerable<string>:

public IEnumerable<string> Max_One {
    get {
        yield return c.x;
        yield return c.y;
        yield return c.z;
    }
}

The values returned in this enumerable would be retrieved only when the property getter is invoked. Hence, the resulting enumerable would always contain the current values of c.x, c.y y c.z.

You can then iterate over these values with a foreach loop as alluded to by yourself in your question.

This might not be practical if you need to gradually assemble the list of variables; in that case, you might have to work with reflection. If this is really required, please let me know; I can provide an example for that, but it will become more verbose and complex.

Respondido 31 Jul 12, 15:07

Thanks Mapper. This is just to check the data we pull in from SQL so it has acceptable value (like for integer there will be a range). SO, I was thinking of storing the variables of similar types and range in a list or array and then loop through. Not sure if this is the right way to do it. Thanks. - MG_UK

Hi, One more question. Is there a way to get the variable name ('c.x' in the example above) in foreach loop later? Thanks very much. - MG_UK

@MG_UK: No, that'll be very hard to do generically. Even when doing it the reflection way, there is no telling via reflection what variable (pointer!) you are accessing a given object instance from, and even then, local variable names may not even make it into the compiled binary without debug information. - OR Mapper

Yes, e.g. if they are all strings:

public List<string> Max_One = new List<string> {c.x,c.y,c.z};

Esto usa el inicializador de colección sintaxis.

It doesn't make sense to compare a string a una int, though. This is a valid example:

  foreach (string var in Max_One)
  {                   
      if (string.IsNullOrEmpty(var))
      {
        // some code here
      }
  }

Respondido 31 Jul 12, 14:07

If your properties are numbers (int, for example) you can do this:

List<int> Max_One = new List<int> { c.x, c.y, c.Z };

y usa tu foreach como este

foreach(int myNum in Max_One) { ... } //you can't name an iterator 'var', it's a reserved word

Reemplaza int in list declaration with the correct numeric type (double, decimal, Etc.)

Respondido 31 Jul 12, 14:07

Podrías intentar usar:

List<object> list = new List<object>
{
  c.x,
  c.y,
  c.z  
};

Respondido 31 Jul 12, 14:07

I will answer your question in reverse way

To start with , you cannot name your variable with "var" since it is reserved name. So what you can do for the foreach is

foreach (var x in Max_One)
      {                   
          if ((x< 0) || (x> 1 ))
          {
            // some code here
          }
      }

if you have .Net 3.0 and later framework, you can use "var" to define x as a member of Max_One list without worrying about the actual type of x. if you have older than the version 3.0 then you need to specify the datatype of x, and in this case your code is valid (still risky though)

The last point (which is the your first point)

public List Max_One = new List {c.x,c.y,c.z}

There are main thing you need to know , that is in order to store in a list , the members must be from the same datatype, so unless a , b , and c are from the same datatype you cannot store them in the same list EXCEPT if you defined the list to store elements of datatype "object". If you used the "Object" method, you need to cast the elements into the original type such as:

var x = (int) Max_One[0];

You can read more about lists and other alternatives from this website http://www.dotnetperls.com/collections

P.s. if this is a homework, then you should read more and learn more from video tutorials and books ;)

Respondido 31 Jul 12, 15:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.