I have an online research project , and also there is lots of multiple choice question. for example...↓
Q:Which Programming language u like?
1,C
2,C++
3,CSharp
4,VB.NET
5,JAVA
I will save the selected item as 1 and unselected as 0
so the result is like↓
People Selected
people1 00100
people2 11100
people3 00110
people4 00100
people5 NULL
... ...
Now my question is how can I create a one-way table like below by the struct like above use Linq?
TOTAL (N=5)
C 1
C++ 1
CSharp 4
VB.NET 1
JAVA 0
NULL 1
This is my source , and I think it is not good
static vo开发者_开发技巧id 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();
}
Please anybody can give me some good idea about it?
thanks for your advice...
dic.Select(a=>
{
Option = a.Value,
Count = lstM.Where(o => o.Length > a.Key && o[a.Key] == '1').Count()
});
this will give you:
C 1
C++ 1
CSharp 4
VB.NET 1
JAVA 0
Lose all the binary encoding and "string typing". Quick example:
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);
This creates a dictionary of selected answers for each person asked. Later you can use LINQ grouping and aggregation operators to produce the result you want.
C: 1
C++: 1
C#: 4
VB.NET: 1
Java: 0
I used string
type for answer options as an example, it can be some other type. The point is to use reference equality and not mess with binary representation. Leave this stuff to lower-lever languages and make sure that your code is not only smart, but also easy to read and maintain.
精彩评论