我有一个在线研究项目,还有很多选择题。 例如...↓
问:您喜欢哪种编程语言?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();
}
请有人能给我一些好主意吗?
感谢您的建议......
答案 0 :(得分: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
答案 1 :(得分: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
类型作为答案选项作为示例,它可以是其他类型。关键是要使用引用相等而不是混淆二进制表示。将这些内容留给低级语言,确保您的代码不仅智能,而且易于阅读和维护。