Click here to Skip to main content
14,423,094 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have a table in my database whose fields' name are like:
X1, X2, X3, ... , X10

I want to select the value of these columns and assign it to a variable. I don't want to write:
V[1] = _MyTable.X1; 
V[2] = _MyTable.X2;
V[10] = _MyTable.X10;

I am looking for something like a loop:
for (int i=1; i<=10; i++) 
    string _FieldName = "X" + i;
    V[i] = _MyTable._FieldName

Using C# and EF.

What I have tried:

I have read near similar questions on the web, but I couldn't find my answer.
Updated 27-May-19 20:26pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

What you need is to use something called reflection.

c - Google Search[^]

Reflection (C#) | Microsoft Docs[^]

How C# Reflection Works With Code Examples[^]

To specifically achieve what you want you'd need to do something like this

var entity = new MyEntity();
            entity.X1 = "ValueX1";
            entity.X2 = "ValueX2";
            entity.X3 = "ValueX3";
            entity.X4 = "ValueX4";
            entity.X5 = "ValueX5";
            entity.X6 = "ValueX6";
            entity.X7 = "ValueX7";
            entity.X8 = "ValueX8";
            entity.X9 = "ValueX9";
            entity.X10 = "ValueX10";

            for (int i = 1; i <= 10; i++)
                var propertyName = string.Format(@"X{0}", i);
                var value =      entity.GetType().GetProperty(propertyName).GetValue(entity, null);
// You get the type from the class/object, then the property name (you have to build it since you have weird property names), then make a call to get value on your object to get the properties value.

                Console.WriteLine("Property {0} - Value {1}", propertyName, value);

The above solution returns

Property X1 - Value ValueX1
Property X2 - Value ValueX2
Property X3 - Value ValueX3
Property X4 - Value ValueX4
Property X5 - Value ValueX5
Property X6 - Value ValueX6
Property X7 - Value ValueX7
Property X8 - Value ValueX8
Property X9 - Value ValueX9
Property X10 - Value ValueX10

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100