2016-02-09 22 views
-1

我有一些數據在名爲Poll_1,Poll_2,Poll_3,... Poll_8的屬性中有值。基於答案的C#評分

我需要在此基礎上的標準分數:

對於每個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; 

有沒有更簡單的方法來做到這一點?

+7

這些類型的問題更適合於:http://codereview.stackexchange.com/ –

+0

嗯,它不值得downvote。 – MB34

回答

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變量的客戶端代碼的實現細節(修剪()=「」!)。

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

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(); 
相關問題