我正在尝试为来自数据库调用的值生成计数。我使用if语句来遍历每个值。我是编程的新手,我可以帮助感觉有一个更短的方法来做到这一点,任何建议将不胜感激。
这是我的数据电话:
public List<MarkingOverviewDTO> GetMarkingOverview(int? myModuleID)
{
List<MarkingOverviewDTO> MyMarkingOverview = new List<MarkingOverviewDTO>();
using (var context = new StudentPortalDBEntities1())
{
var myOverview =
from m in context.ModuleDetails
join ms in context.MarkingScheduleOverviews on m.ModuleID equals ms.ModuleFk
join mot in context.MarkingOverviewTitles on ms.MSOverview equals mot.OverviewTitleID
where m.ModuleID == myModuleID
select new
{
mot.TitleName,
ms.Comment1,
ms.Comment2,
ms.Comment3,
ms.Comment4,
ms.Comment5,
ms.Comment6,
ms.Comment7,
ms.Comment8,
ms.Comment9,
ms.Comment10,
};
foreach (var item in myOverview)
{
MyMarkingOverview.Add(new MarkingOverviewDTO
{
OverviewTitle = item.TitleName,
Comment1 = item.Comment1,
Comment2 = item.Comment2,
Comment3 = item.Comment3,
Comment4 = item.Comment4,
Comment5 = item.Comment5,
Comment6 = item.Comment6,
Comment7 = item.Comment7,
Comment8 = item.Comment8,
Comment9 = item.Comment9,
Comment10 = item.Comment10,
//Get the comment count to generate the correct number of checkboxes per row
MyCommentCount = CountComments(item.Comment1, item.Comment2, item.Comment3, item.Comment4, item.Comment5, item.Comment6, item.Comment7, item.Comment8, item.Comment9, item.Comment10),
});
}
}
return MyMarkingOverview;
}
这是我的方法:
/// <summary>
/// Get comment count based on value. This will return a count to generate the correct number of check boxes per overview
/// </summary>
/// <param name="Comment1"></param>
/// <param name="Comment2"></param>
/// <param name="Comment3"></param>
/// <param name="Comment4"></param>
/// <param name="Comment5"></param>
/// <param name="Comment6"></param>
/// <param name="Comment7"></param>
/// <param name="Comment8"></param>
/// <param name="Comment9"></param>
/// <param name="Comment10"></param>
/// <returns></returns>
public int CountComments(string Comment1, string Comment2, string Comment3, string Comment4, string Comment5, string Comment6, string Comment7, string Comment8, string Comment9, string Comment10)
{
var myCommentCount = 0;
if (Comment1 != null)
{
myCommentCount += 1;
}
if (Comment2 != null)
{
myCommentCount += 1;
}
if (Comment3 != null)
{
myCommentCount += 1;
}
if (Comment4 != null)
{
myCommentCount += 1;
}
if (Comment5 != null)
{
myCommentCount += 1;
}
if (Comment6 != null)
{
myCommentCount += 1;
}
if (Comment7 != null)
{
myCommentCount += 1;
}
if (Comment8 != null)
{
myCommentCount += 1;
}
if (Comment9 != null)
{
myCommentCount += 1;
}
if (Comment10 != null)
{
myCommentCount += 1;
}
return myCommentCount;
}
答案 0 :(得分:5)
public int CountComments(params string[] comments)
{
return comments.Count(x => x != null);
}