0

我有一个格式为 csv 的文件

左选择,右选择,左 || 对

其中 LeftChoice 和 RightChoice 是非唯一文本字符串,而 Left || 右边是被选中的字符串。

我想要做的是获得一个包含每个元素的列表:字符串、选择的计数、非选择的计数。

目前我有以下内容:

 var result = from line in file
                     let values = line.Split(',')
                     select new { Choice1 = values[0], Choice2 = values[1],  Result =  values[2].Equals("left")};


        var leftTrue = from dataSet in result
                 where dataSet.Result
                 group dataSet.Choice1 by dataSet.Choice1 into C1
                 select new { Value = C1.Key, Count = C1.Count() };


        var leftFalse = from dataSet in result
                       where !dataSet.Result
                       group dataSet.Choice1 by dataSet.Choice1 into C1
                       select new { Value = C1.Key, Count = C1.Count() };

        var rightTrue = from dataSet in result
                       where !dataSet.Result
                       group dataSet.Choice2 by dataSet.Choice2 into C2
                       select new { Value = C2.Key, Count = C2.Count() };


        var rightFalse = from dataSet in result
                        where dataSet.Result
                        group dataSet.Choice2 by dataSet.Choice2 into C2
                        select new { Value = C2.Key, Count = C2.Count() };

示例输入

 Fred,Cole,left
 Jill,Dave,right
 Pat,Fred,right
 Pat,Pat,left

示例输出:会给

Name Chosen NotChosen
Fred   2        0
Cole   0        1
Jill   0        1
Dave   1        0
Pat    1        2
4

1 回答 1

1

我认为最简单的方法是按名称分组,然后计算名称被选择和未选择的次数。

var result = from line in file
             let values = line.Split(',')
             let left = values[0]
             let right = values[1]
             let leftChosen = values[2].Equals("left")
             let pair = new [] 
                        { 
                            new { Name = left, IsChosen = leftChosen }, 
                            new { Name = right, IsChosen = !leftChosen } 
                        }
             from item in pair
             group item by item.Name into nameGroup
             select new 
                    {
                        Name = nameGroup.Key, 
                        ChosenCount = nameGroup.Count(x => x.IsChosen),
                        NonChosenCount = nameGroup.Count(x => !x.IsChosen)
                    };
于 2012-10-23T04:12:29.243 回答