2011-07-11 72 views
1

我有一個在線研究項目,也有很多選擇題。 例如...↓有沒有一種很好的方式來創建一個由linq多重選擇結果的單向表?

問:你喜歡哪種編程語言?

1,C 
2,C++ 
3,CSharp 
4,VB.NET 
5,JAVA 

我會選擇的項目保存爲1和未選定爲0

所以結果是像↓

People  Selected 
people1  00100 
people2  11100 
people3  00110 
people4  00100 
people5  NULL 
... ... 

現在我的問題是我怎麼可以創建一個單向的表樣下面的結構像上面那樣使用Linq?

TOTAL  (N=5) 
C   1 
C++  1 
CSharp  4 
VB.NET  1 
JAVA  0 
NULL  1 

這是我的來源,我認爲這是不好的

static void Main(string[] args) 
{ 
    // the mapping... 
    Dictionary<int, string> dic = new Dictionary<int, string>() 
    { 
     {0 , "C"} , 
     {1 , "C++"} , 
     {2 , "CSharp"} , 
     {3 , "VB.NET"} , 
     {4 , "JAVA"} 
    }; 

    // the answer data by the people 
    List<string> lstM = new List<string>() 
    { 
     "00100" , // people1 
     "11100" , // people2 
     "00110" , // people3 
     "00100" , // people4 
     "NULL" // people5 
    }; 

    var result = from p in lstM 
       where "NULL".Equals(p) 
       group p by p into g 
       select new {Key = g.Key , Cnt = g.Count()}; 

    foreach (var d in dic) 
    { 
     var tmp1 = from p in lstM 
       where !"NULL".Equals(p) && "1".Equals(p.Substring(d.Key, 1)) 
       select 1; 

     Console.WriteLine(string.Format("Key = {0} , Cnt={1}", dic[d.Key], tmp1.Count())); 
    } 

    foreach (var x in result) 
    { 
     Console.WriteLine(string.Format("Key = {0} , Cnt={1}", x.Key, x.Cnt)); 
    } 

    Console.ReadKey(); 
} 

請任何人都可以給我一些關於它的好主意嗎?

感謝您的意見...

回答

2
dic.Select(a=> 
{ 
    Option = a.Value, 
    Count = lstM.Where(o => o.Length > a.Key && o[a.Key] == '1').Count() 
}); 

這會給你:

C   1 
C++  1 
CSharp  4 
VB.NET  1 
JAVA  0 
+0

謝謝你,這是非常容易閱讀~~~ – shenhengbin

1

失去所有的二進制編碼和「字符串類型」。快速示例:

var options = new [] { "C", "C++", "C#", "VB.NET", "Java" }; 

var people1 = new string[] { "C#" }; 
var people2 = new string[] { "C", "C++", "C#" }; 
var people3 = new string[] { "C#", "VB.NET" }; 
var people4 = new string[] { "C#" }; 
var people5 = new string[] { }; 

var pollAnswers = new [] { options, people1, people2, people3, people4, people5 }; 

pollAnswers.SelectMany(answ => answ). 
      GroupBy(opt => opt). 
      ToDictionary(gr => gr.Key, gr => gr.Count() -1); 

這會爲每個要求的人創建一個選定答案的字典。稍後,您可以使用LINQ分組和聚合操作符來生成所需的結果。

C: 1 
C++: 1 
C#: 4 
VB.NET: 1 
Java: 0 

我用string類型答案選項作爲一個例子,它可以是某種其它類型。重點是使用引用相等,而不是混淆二進制表示。把這些東西留在低級語言中,並確保你的代碼不僅聰明,而且易於閱讀和維護。

+0

謝謝~~這是一個好主意...... – shenhengbin

相關問題