gpt4 book ai didi

c# - 用几个 if-else 语句重构 foreach 循环

转载 作者:行者123 更新时间:2023-11-30 23:32:46 25 4
gpt4 key购买 nike

如果 SPListItem 的某些字段为 null 并且如果为该属性,则我会多次检查此方法,然后为该属性写入默认值。有什么办法可以减少这段代码吗?谢谢

public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic)
{
List<Models.EmployeeInfo> listEmployeeInfo = new List<Models.EmployeeInfo>();

foreach (SPListItem item in splic)
{
var employeeInfo = new Models.EmployeeInfo();

if (item["EmployeeName"] == null)
{
employeeInfo.EmployeeName = "";
}
else
{
employeeInfo.EmployeeName = item["EmployeeName"].ToString();
}

if (item["Position"] == null)
{
employeeInfo.Position = "";
}
else
{
employeeInfo.Position = item["Position"].ToString();
}

if (item["Office"] == null)
{
employeeInfo.Office = "";
}
else
{
employeeInfo.Office = item["Office"].ToString();
}

if (item["IsPublic"] == null)
{
employeeInfo.IsPublic = true;
}
else
{
employeeInfo.IsPublic = Convert.ToBoolean("IsPublic");
}

listEmployeeInfo.Add(employeeInfo);
}

return listEmployeeInfo;
}

最佳答案

您可以使用一些反射来设置属性。然后你可以遍历所有属性名的列表并设置它们。(这样当一个属性被添加到模型中时,您需要做的就是将它添加到字符串列表中)

public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic)
{
var listEmployeeInfo = new List<Models.EmployeeInfo>();
var propertyNames = new List<string>(){"EmployeeName","Position","Office","IsPublic"}

foreach (SPListItem item in splic)
{
var employeeInfo = new Models.EmployeeInfo();

foreach (var propertyName in propertyNames)
{
string newData = "";
if (item[propertyName] != null)
{
newData = item[propertyName];
}
employeeInfo.GetType().GetProperty(propertyName).SetValue(employeeInfo, newData, null);
}

listEmployeeInfo.Add(employeeInfo);
}
return listEmployeeInfo;
}

关于c# - 用几个 if-else 语句重构 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34184602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com