Reputation: 732
I have an ordered list and would like to assign those value to a class.
List<string> listValue = new List<string>()
{
"Hello",
"Hello2",
"Hello3",
}
public class SampleClass
{
public string _VarA {get; set;}
public string _VarB {get; set;}
public string _VarC {get; set;}
//around 40 attribute
}
any other methods instead of below method
SampleClass object = new SampleClass();
object._VarA = listValue.get(0);
object._VarB = listValue.get(1);
object._VarC = listValue.get(2);
//Sample
object._VarA = "Hello"
object._VarB = "Hello2"
object._VarC = "Hello3"
//until end of this class variable
Upvotes: 0
Views: 13224
Reputation: 903
You can achieve this using reflection
SampleClass obj = new SampleClass();
int i = 0;
foreach (var item in typeof(SampleClass).GetProperties()) // (or) obj.GetType().GetProperties()
{
item.SetValue(obj, listValue[i++].ToString());
}
Upvotes: 1
Reputation: 188
You can try reflection class as following:
class test
{
public string var1;
public string var2;
public string var3;
}
class Program
{
static void Main(string[] args)
{
List<string> testList = new List<string>();
testList.Add("string1");
testList.Add("string2");
testList.Add("string3");
test testObj = new test();
var members = testObj.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
for (int i = 0; i < members.Length; i++)
{
members[i].SetValue(testObj, testList[i]);
}
}
}
In GetFields() method, please notice binding flags. Use Nonpublic for Private variables.
Upvotes: 1
Reputation: 250
If the properties are to be assigned in alphabetical order, you could use reflection to assign the values:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
var listValue = new List<string>()
{
"Hello",
"Hello2",
"Hello3",
};
var sampleClass = new SampleClass();
var sampleType = sampleClass.GetType();
var properties = sampleType.GetProperties().OrderBy(prop => prop.Name).ToList();
for (int i = 0; i < listValue.Count; i++)
{
if (i < properties.Count)
{
properties[i].SetValue(sampleClass, listValue[i]);
Console.WriteLine(properties[i].Name + " = " + listValue[i]);
}
}
Console.ReadLine();
}
public class SampleClass
{
public string _VarA { get; set; }
public string _VarB { get; set; }
public string _VarC { get; set; }
//around 40 attribute
}
}
Upvotes: 1