日期:2014-05-18  浏览次数:20723 次

面试题求解
有一个日志文件,记录如下,用空格分隔

访问ID 访问时间 访问URL

用C# 按访问次数多到少排列URL (URL不能重复)



------解决方案--------------------
探讨
IO读日志
split取URL
Dictionary保存URL和次数

------解决方案--------------------
txt中的内容
id da url
1 201001 a
2 201002 b
3 201003 c
4 201004 d
5 201005 a
6 201006 b
7 201007 a

代码:
private void button2_Click(object sender, EventArgs e)
{
string filename = "e:/u.txt";
StreamReader rd = new StreamReader(filename, Encoding.Default);
string[] svals;
DataTable dt = new DataTable();
int i = 0;
while (!rd.EndOfStream)
{
string sline = rd.ReadLine();
svals = sline.Split(' ');
if (i == 0)
{
foreach (string val in svals)
{
dt.Columns.Add(val, typeof(string));
}
}
else
{
DataRow dr = dt.NewRow();
dr["id"] = svals[0];
dr["da"] = svals[1];
dr["url"] = svals[2];
dt.Rows.Add(dr);
}
i++;
}
dataGridView1.DataSource = dt;

var m = from p in dt.AsEnumerable() group p.Field<string>("url") by p.Field<string>("url") into g orderby g.Count() descending select new {code=g.Key,nums=g.Count() };
foreach (var val in m)
{
MessageBox.Show(val.code + " " + val.nums);
}

}
------解决方案--------------------
string filename = "e:/u.txt";
StreamReader rd = new StreamReader(filename, Encoding.Default);
string[] svals;
DataTable dt = new DataTable();
int i = 0;
while (!rd.EndOfStream)
{
string sline = rd.ReadLine();
svals = sline.Split(' ');
if (i == 0)
{
foreach (string val in svals)
{
dt.Columns.Add(val, typeof(string));
}
}
else
{
DataRow dr = dt.NewRow();
dr["id"] = svals[0];
dr["da"] = svals[1];
dr["url"] = svals[2];
dt.Rows.Add(dr);
}
i++;
}
// dataGridView1.DataSource = dt.DefaultView.Sort ="id";
DataRow[] row = dt.Select("", "id");
DataTable dt1 = dt.Clone();
for (int o = 0; o < row.Length; o++)
{
if (dt1.Rows.Count == 0)
{
DataRow row1 = dt1.NewRow();
row1["id"] = row[o]["id"];
row1["da"] = row[o]["da"];
row1["url"] = row[o]["url"];
dt1.Rows.Add(row1);
}
else
{
DataRow[] row2 = dt1.Select("url ='"+row[o]["url"].ToString()+"'");
if (row2.Length == 0)