Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (1 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:
C#
V[1] = _MyTable.X1; 
V[2] = _MyTable.X2;
.
.
.
V[10] = _MyTable.X10;


I am looking for something like a loop:
C#
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.
Posted
Updated 27-May-19 19:26pm

1 solution

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

C#
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

Quote:
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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900