public void StopShooting() { foreach (var item in allScore) { //计算总成绩 float totalScore = 0; //计算脱靶数 int missNum = 0; //计算击中数 int hitNum = 0; //计算开枪数 int guns; //计算平均成绩 float averageScore; string grading; for (int i = 0; i < item.Value.Count; i++) { totalScore += item.Value[i].hitNum; if (item.Value[i].hitFlag==0)//0是未击中 1是击中 missNum += 1; else hitNum += 1; } guns = item.Value.Count; averageScore = totalScore / guns; grading = GetGrading(averageScore); //每个人射击总的数据 Score score = new Score() { id = item.Key.ToString(), createTime = item.Value[0].startTime, totalScore = totalScore.ToString(), hitNum = hitNum.ToString(), missNum = missNum.ToString(), grading = grading, guns = guns.ToString(), turnType = item.Value[0].shootingMode.ToString(), turnTheme = item.Value[0].baJiType, playerName = PersonDao.Instance.FindNameByID(item.Key.ToString()).namee, workPlace = item.Value[0].workPlace }; //将数据添加到数据库中 ScoreInfoSqlMgr.Instance.Add(score); } //停止射击 要把存的所有的成绩给清空一下 allScore.Clear(); //存的顺序的也要清空一下 dicScore.Clear(); //不接受射击成绩的消息了 isRecive = false; }这段代码如何优化
时间: 2023-06-04 10:03:03 浏览: 112
TCP/UDP网络调试助手
3星 · 编辑精心推荐
这段代码的优化可以从以下几个方面入手:
1. 使用 LINQ 语句来优化 foreach 循环
2. 使用 try catch 块来处理插入数据库时的异常情况
3. 将重复的代码封装成方法来优化代码的复用性
经过优化后的代码如下所示:
```
public void StopShooting()
{
// 使用 LINQ 语句计算总成绩、脱靶数、击中数、平均成绩、分数等信息
var scoreList = allScore.Select(item => new Score
{
id = item.Key.ToString(),
createTime = item.Value[0].startTime,
totalScore = item.Value.Sum(x => x.hitNum).ToString(),
hitNum = item.Value.Count(x => x.hitFlag == 1).ToString(),
missNum = item.Value.Count(x => x.hitFlag == 0).ToString(),
guns = item.Value.Count.ToString(),
turnType = item.Value[0].shootingMode.ToString(),
turnTheme = item.Value[0].baJiType,
playerName = PersonDao.Instance.FindNameByID(item.Key.ToString()).namee,
workPlace = item.Value[0].workPlace,
grading = GetGrading(item.Value.Average(x => x.hitNum))
}).ToList();
// 将数据添加到数据库中,并处理异常情况
try
{
ScoreInfoSqlMgr.Instance.Add(scoreList);
}
catch (Exception ex)
{
Console.WriteLine("插入数据库失败:" + ex.Message);
}
// 停止射击,清空所有成绩,存储顺序,不再接受射击成绩
allScore.Clear();
dicScore.Clear();
isRecive = false;
}
// 获取射击分数等级
public string GetGrading(double score)
{
if (score >= 90)
return "优秀";
else if (score >= 80)
return "良好";
else if (score >= 60)
return "及格";
else
return "不及格";
}
// 定义成绩类
public class Score
{
public string id { get; set; }
public DateTime createTime { get; set; }
public string totalScore { get; set; }
public string hitNum { get; set; }
public string missNum { get; set; }
public string grading { get; set; }
public string guns { get; set; }
public string turnType { get; set; }
public string turnTheme { get; set; }
public string playerName { get; set; }
public string workPlace { get; set; }
}
```
阅读全文