Reputation: 6540
I have a list of c# objects and each object has 100 properties:
public string Group1;
public string Group2;
public string Group3;
.....................
...
..
.
public string Group99;
public string Group100;
I want to be able to pass in two numbers in the range of 1 to 100 and only get the properties that fall in between that range.
for example if i pass in the number 31 to 50 i would want the properties:
public string Group31;
public string Group32;
....................
...
..
.
public string Group50;
how would I be able to achieve this?
Upvotes: 1
Views: 99
Reputation: 5398
In your case you have fields, so you can use reflection and LINQ like this:
//pass your class to typeof
var ClssType = typeof (SomeCLass);
ClssType.GetFields().OrderBy(n=>n.Name).Skip(30).Take(19).ToList();
In Skip you passing numbers that you want to skip befaure taking fields.
If you had properties you could use .GetProperties()
instead of .GetFields()
For getting values of your properties you need to call .GetValue(obj, null)
for every object in your array.
//let say you have array of objects myObj[] then your code will look like this:
var fieldsInfos = ClssType.GetFields().OrderBy(n=>n.Name).Skip(30).Take(19).ToList();
//go thorugh your array
foreach(var obj in myObj)
{
//go through fields
foreach(var field in fieldsInfos)
{
//get value of field by calling
Console.WriteLine(field.GetValue(obj, null));
}
}
Upvotes: 1