0

我的文件是:

outlook temperature Humidity Windy PlayTennis 

sunny hot high false N

sunny hot high true N

overcast hot high false P

rain mild high false P

rain cool normal false P

我从文件中发现了独特的元素:

element:occurence

suny :2 

overcast:1 

rain:2

mild:1

cool:1

hot :4

normal:1

high:2

false:4

true:1 

n:2

p:3

然后我删除了出现次数小于 1 的元素。

输出如下:

suny : 2
rain: 2
hot :3
high:4
false:4
n:2 
p:3

现在我想要输出为(从第一个输出开始,它应该与所有其他元素循环以形成一组两个频繁集)

element:occurence

sunny,hot:2
sunny,high:2
sunny,false:1
sunny,n:2
sunny,p:0
rain,hot:0
rain,high:1
rain,false:2
rain,n:0
rain,p:2
hot,high:2
hot,false:1
hot,n:2
hot,p:0
and so on..

这是我的代码:

var occurences = File.ReadAllLines(file)
    .Skip(1)
    .SelectMany(l => l.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries))
    .GroupBy(w => w)
    .ToDictionary(g => g.Key, g => g.Count());

foreach(var pair in occurences)
    label1.Text += String.Format("{0}: {1}\n", pair.Key, pair.Value);

我实现了这个来找到第一个频繁集。

对于第二个我该怎么办?

我还需要找到第三组。

4

1 回答 1

0

我将从重构开始。1)创建一个类来保存数据项

public class WeatherForecast
{
    public string Outlook { get; set; }
    public string Temperature { get; set; }
    public string Humidity { get; set; }
    public bool Windy { get; set; }
    public string PlayTennis { get; set; }
}

然后创建你的对象;

var forecasts = new List<WeatherForecast>();
foreach(var line in File.ReadLines(file).Skip(1))
{
    var values = line.Split(' ');
    forecasts.Add(new WeatherForecast
                      {
                          Outlook = values[0],
                          Temperature = values[1],
                          Humidity = values[2],
                          Windy = Convert.ToBoolean(values[3]),
                          PlayTennis = values[4]
                      });
}

然后,您也许能够弄清楚您想如何使用 Linq 查询数据。

有关分组帮助,请参阅LINQ Group By Multiple fields -Syntax help

//Group by 1 key
forecasts.GroupBy(f => new { f.Outlook }, (key, group) => new { Key1 = key.Outlook, Count = group.Count() });

//Group by 2 keys
forecasts.GroupBy(f => new { f.Outlook, f.Temperature }, (key, group) => new { Key1 = key.Outlook, Key2 = key.Temperature , Count = group.Count()});

//Group by 3 keys
forecasts.GroupBy(f => new { f.Outlook, f.Temperature, f.Humidity }, (key, group) => new { Key1 = key.Outlook, Key2 = key.Temperature, Key3 = key.Humidity, Count = group.Count()});

结果:

在此处输入图像描述

于 2013-02-27T01:30:57.693 回答