我有一些数据在名为Poll_1,Poll_2,Poll_3,... Poll_8的属性中具有值。
我需要根据这个标准得分:
对于非空的每个Poll_1至Poll_4,FirstPollCount递增 对于非空的每个Poll_5至Poll_8,SecondPollCount递增。
目前我正在这样做。
int pass1 = 0;
int pass2 = 0;
if (rec.Poll_1.Trim() != "") { pass1++; };
if (rec.Poll_2.Trim() != "") { pass1++; };
if (rec.Poll_3.Trim() != "") { pass1++; };
if (rec.Poll_4.Trim() != "") { pass1++; };
if (rec.Poll_5.Trim() != "") { pass2++; };
if (rec.Poll_6.Trim() != "") { pass2++; };
if (rec.Poll_7.Trim() != "") { pass2++; };
if (rec.Poll_8.Trim() != "") { pass2++; };
aa.FirstPollCount = pass1;
aa.SecondPollCount = pass2;
有更简单的方法吗?
答案 0 :(得分:1)
不是更好,但是如果你想寻找另一种选择
List<string> firstPolls = new List<string>()
{
rec.Poll_1.Trim(), rec.Poll_2.Trim(),rec.Poll_3.Trim(),rec.Poll_4.Trim()
};
int pass1 = firstPolls.Count(x => x != "");
List<string> secondPolls = new List<string>()
{
rec.Poll_5.Trim(), rec.Poll_6.Trim(),rec.Poll_7.Trim(),rec.Poll_8.Trim()
};
int pass2= secondPolls.Count(x => x != "");
顺便说一句, rec 变量的类是什么?可能的改进是添加一个执行此代码并返回值的内部方法:
int pass1 = rec.GetFirstScoreCount();
int pass2 = rec.GetSecondScoreCount();
从而隐藏了使用rec变量的客户端代码中的实现细节(Trim()!=&#34;&#34;)。
答案 1 :(得分:1)
您可以使用Linq:
string s1 = "Random String";
string s2 = "Random String";
string s3 = "Random String";
string s4 = "Random String";
string s5 = "Random String";
string s6 = "";
string s7 = "Random String";
string s8 = "Random String";
int countPool1 = (new List<string>(){s1, s2, s3, s4}).Count(t => t.Trim() != "");
int countPool2 = (new List<string>() { s5, s6, s7, s8 }).Count(t => t.Trim() != "");
Console.Out.WriteLine("Pool 1 : " + countPool1);
Console.Out.WriteLine("Pool 2 : " + countPool2);
输出:
游泳池1:4
游泳池2:3
答案 2 :(得分:1)
您还可以使用Linq查询语法:
List<string> pol1to4Coll = new List<string>() { rec.Poll_1, rec.Poll_2, rec.Poll_3, rec.Poll_4 };
List<string> pol5to8Coll = new List<string>() { rec.Poll_5, rec.Poll_6, rec.Poll_7, rec.Poll_8 };
int countPol1to4Coll = (from poll in pol1to4Coll
where poll != ""
select poll).Count();
int countPol5to8Coll = (from poll in pol5to8Coll
where poll != ""
select poll).Count();