将tag直接保存在文章的表中,如Tag字段,tag为“c#”和“.net”,则Tag字段值为“c#/.net”就是依/符号分割tag,这样数据库中保存的是字符串了。单文章显示的时候可以直接分割成数组显示,减少表的关联,提高了效率。 当需要显示最近流行词的时候。 查询所有的tag select tag from 表 利用DataReader把输出结果相加起来。然后根据分隔符转化为字符串,剩下的就是对字符串进行排序,根据tag重多少进行。并返回重复的数量,见代码。为方便查看,我都写在了一个aspx页面中了。
protected string stext; protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); using (System.Data.SqlClient.SqlDataReader rd = XXXX.DBUtility.SqlHelper.ExecuteReader(SqlHelper.ConnectionString, System.Data.CommandType.Text, "Select Kinds + '/' FROM XXX", null)) { while (rd.Read()) { sb.Append(rd.GetString(0)); } } stext = sb.ToString();
ToArrayBySort(ToArray(stext, '/'));
}
/// <summary> /// 将字符串根据分隔符转化为数组 /// </summary> /// <param name="sourcestring">要转化的字符串</param> /// <param name="compart">分隔符</param> /// <returns></returns> public ArrayList ToArray(string sourcestring, char split) { CharEnumerator ce = sourcestring.GetEnumerator(); StringBuilder sb = new StringBuilder(); ArrayList slist = new ArrayList();
while (ce.MoveNext()) { if (ce.Current != split) { sb.Append(ce.Current); } else { if (string.Empty == sb.ToString()) continue; slist.Add(sb.ToString()); sb.Remove(0, sb.ToString().Length); } } return slist; }
public class myComparer : IComparer { int IComparer.Compare(Object x, Object y) { return ((new CaseInsensitiveComparer()).Compare(((SortItem)y).Count, ((SortItem)x).Count)); } }
public class SortItem { private string itemname; private int count; public SortItem() { } public string ItemName { get { return itemname; } set { itemname = value; } } public int Count { get { return count; } set { count = value; } } }
public System.Collections.Generic.IList<SortItem> ToArrayBySort(ArrayList slist) { slist.Sort(); ArrayList sortList = new ArrayList(); foreach (object obj in slist) { SortItem sItem = new SortItem(); sItem.ItemName = obj.ToString(); sItem.Count = 1; if (sortList.Count == 0) { sortList.Add(sItem); continue; } if (obj.ToString() == ((SortItem)sortList[sortList.Count - 1]).ItemName) { sItem.Count = ((SortItem)sortList[sortList.Count - 1]).Count + 1; sortList.RemoveAt(sortList.Count - 1); } sortList.Add(sItem); } myComparer myCm = new myComparer(); sortList.Sort(myCm);