Reputation: 527
I have class
like this
public class EmployeeInfo
{
public string EmployeeName { get; set; }
public string PhoneNumber { get; set; }
public string Office { get; set; }
public string Department { get; set; }
}
I've created method that takes SPListItemCollection
as parameter and returns list of object of EmployeeInfo
class.There is no restrictions inside SPList
and when you create new item you can leave some of the fields empty, so I've used reflection
to determine if field is null
and then insert empty string when populating EmployeeInfo
object to avoid exceptions.
public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic)
{
var listEmployeeInfo = new List<Models.EmployeeInfo>();
var propertyNames = new List<string>() { "EmployeeName",
"Department",
"Office",
"PhoneNumber"};
foreach (SPListItem item in splic)
{
var employeeInfo = new Models.EmployeeInfo();
foreach (var propertyName in propertyNames)
{
string newData = "";
if (item[propertyName] != null)
{
newData = item[propertyName].ToString();
}
employeeInfo.GetType().GetProperty(propertyName).SetValue(employeeInfo, newData, null);
}
listEmployeeInfo.Add(employeeInfo);
}
return listEmployeeInfo;
}
Later I've learned that it is bad practice to use reflection
inside of nested loops , so I'm looking for different approach.
Is there any chance I can make some pre Validation Rules inside EmpployeeInfo
class , something like Validation method or to write some code inside class properties and than inside of GetEmployeeInfo
method just to populate properties by calling that method?
Thank you.
Upvotes: 0
Views: 324
Reputation: 308
just write c'tor:
public EmployeeInfo(string employeeName ,string phoneNumber, string office, string department)
{
EmployeeName = employeeName;
PhoneNumber = phoneNumber;
Office = office;
Department = department;
}
and you can call it like this:
var employeeInfo = new Models.EmployeeInfo(item["EmployeeName"] ?? "", item["PhoneNumber"] ?? "", item["Office"] ?? "", item["Department"] ?? "");
anyway, you should avoid declaring fields as public, as it breaks encapsulation.
Upvotes: 1
Reputation: 571
You could just add the logic in the seperate getters and setters
public class EmployeeInfo
{
private string employeeName;
public string EmployeeName
{
get
{
return employeeName ?? ""; //Returns the content, or an empty string if it is null
}
set
{
employeeName = value;
}
}
}
This way you get a standard value (say ""
) instead of null when accessing the property.
Upvotes: 0