日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

c# SortedList的妙用 (GroupBy)

發布時間:2025/3/21 C# 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c# SortedList的妙用 (GroupBy) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
公司做一個藥品監控系統(web),目前負責對監控問題添加屏蔽規則功能。由于藥品問題要分成 問題級別 - 問題類型 - 問題具體結果類型 三層級別,以這三個級別,分成大組,再分成小組。由于本人煩于寫存儲過程,在sql 中使用語句頻繁查詢,性能又不好。于是想到利用
SortedList的自動排序和分組的功能,做了一個模板。覺得挺好用的,分享一下!

?? ??? 數據結構如下:

namespace CRMS.Web.Query.ProblemPrescription {public partial class ProblemDetail : CRMS.Web.Base.BasePage{// 由于datarow的構造函數是protected,這里巧妙地構造自定義table, 可以獲取自定義datarowprivate DataTable simpleTable = null;public DataTable SimpleTable{set { this.simpleTable = value; }get{if (simpleTable == null){simpleTable = new DataTable();System.Type stringType = System.Type.GetType("System.String");simpleTable.Columns.Add(new DataColumn("cli_lvl_code", stringType));simpleTable.Columns.Add(new DataColumn("cli_lvl_name", stringType));simpleTable.Columns.Add(new DataColumn("cli_title_code", stringType));simpleTable.Columns.Add(new DataColumn("cli_title_name", stringType));simpleTable.Columns.Add(new DataColumn("id", stringType)); // 以 "id" 代替 "cli_analyze_title"}return this.simpleTable;}}private result_data result_data;public result_data Result_data{set { this.result_data = value; }get { return this.result_data; }}public partial class result_data{private result_level[] result_levelField;public result_level[] result_level{get { return this.result_levelField; }set { this.result_levelField = value; }}private string nameField;[System.Xml.Serialization.XmlAttributeAttribute("name")]public string name{get { return this.nameField; }set { this.nameField = value; }}}public partial class result_level{private string nameField;[System.Xml.Serialization.XmlAttributeAttribute()]public string name{get { return this.nameField; }set { this.nameField = value; }}private result_title[] result_titleField;[System.Xml.Serialization.XmlElementAttribute("result_title", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]public result_title[] result_title{get { return this.result_titleField; }set { this.result_titleField = value; }}}public partial class result_title{private string nameField;public string name{get { return this.nameField; }set { this.nameField = value; }}private result[] resultField;public result[] result{get { return this.resultField; }set { this.resultField = value; }}}[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")][System.SerializableAttribute()][System.Diagnostics.DebuggerStepThroughAttribute()][System.ComponentModel.DesignerCategoryAttribute("code")][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public partial class result{private title titleFiled;[System.Xml.Serialization.XmlElementAttribute("title", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]public title Title{get { return this.titleFiled; }set { this.titleFiled = value; }}private detail detailFiled;[System.Xml.Serialization.XmlElementAttribute("detail", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]public detail Detail{get { return this.detailFiled; }set { this.detailFiled = value; }}private reference referenceFiled;[System.Xml.Serialization.XmlElementAttribute("reference", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]public reference Reference{get { return this.referenceFiled; }set { this.referenceFiled = value; }}public string mediA_hiscode;public string mediB_hiscode;public string result_type;public string result_id;}public partial class title{private string nameField;private string valueField;public string Name{get { return this.nameField; }set { this.nameField = value; }}public string Value{get { return this.valueField; }set { this.valueField = value; }}}public partial class detail{private string valueField;public string Value{get { return this.valueField; }set { this.valueField = value; }}}[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")][System.SerializableAttribute()][System.Diagnostics.DebuggerStepThroughAttribute()][System.ComponentModel.DesignerCategoryAttribute("code")][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public partial class reference{private string referenceField;[System.Xml.Serialization.XmlTextAttribute()]public string Value{get { return this.referenceField; }set { this.referenceField = value; }}}}// class ProblemDetail// 各個比較器和等價器public class lvl_title_id_comparer : IComparer<DataRow>{public int Compare(DataRow x, DataRow y){int res = string.Compare(x["cli_lvl_code"].ToString(), y["cli_lvl_code"].ToString());if (res != 0){return res;}else{res = string.Compare(x["cli_title_code"].ToString(), y["cli_title_code"].ToString());if (res != 0){return res;}else{return string.Compare(x["id"].ToString(), y["id"].ToString());}}}}public class lvl_title_comparer : IComparer<DataRow>{public int Compare(DataRow x, DataRow y){int res = string.Compare(x["cli_lvl_code"].ToString(), y["cli_lvl_code"].ToString());if (res != 0){return res;}else{return string.Compare(x["cli_title_code"].ToString(), y["cli_title_code"].ToString());}}}public class lvl_comparer : IComparer<DataRow>{public int Compare(DataRow x, DataRow y){return string.Compare(x["cli_lvl_code"].ToString(), y["cli_lvl_code"].ToString());}}public class lvl_title_equalitycomparer : IEqualityComparer<DataRow>{public bool Equals(DataRow x, DataRow y){return x["cli_lvl_code"].ToString() == y["cli_lvl_code"].ToString() &&x["cli_title_code"].ToString() == y["cli_title_code"].ToString();}public int GetHashCode(DataRow obj){return obj.ToString().GetHashCode();}}public class lvl_equalitycomparer : IEqualityComparer<DataRow>{public bool Equals(DataRow x, DataRow y){return x["cli_lvl_code"].ToString() == y["cli_lvl_code"].ToString();}public int GetHashCode(DataRow obj){return obj.ToString().GetHashCode();}} }


具體實現函數:

/// <summary>/// 獲取問題類型、問題標題/// </summary>protected void GetProLvl(){UserParamsClass user = Session["user"] as UserParamsClass;string hosp_code = "";if (user != null){hosp_code = user.strAreaCode;}if (hosp_code == "")hosp_code = "%";string strSQL = string.Empty;string strTmp = string.Empty;// 查詢問題結果詳細信息strTmp = @"SELECT a.id ,a.cli_lvl_code,a.cli_title_code,a.cli_analyze_title,a.cli_analyze_reference,a.cli_analyze_addition,a.encode_type,c.sys_name as cli_lvl_name,d.sys_name as cli_title_name,b.sys_name as cli_result_name,{0} as is_op_ipFROM {1} as aleft join comh_syslang as b on a.cli_result_code=b.sys_code left join comh_syslang as c on a.cli_lvl_code=c.sys_codeleft join comh_syslang as d on a.cli_title_code=d.sys_codewhere a.acquisition_time='{2}' and a.hos_hosp_code like '{3}' and a.cli_adm_no='{4}' and a.source_type=1 and a.is_del=0 and not exists (select distinct b.id from homh_user_analyze_rules_req as bwhere a.source_type=1 and a.source_type=b.source_type and a.cli_drug_code_a=b.edt_item1 and isnull(a.cli_drug_code_b,'')=isnull(b.edt_item2,'') and a.cli_result_type=b.edt_analyze_type and b.is_op_ip in({0},3) and b.status=1 and a.hos_hosp_code=b.hos_hosp_code) order by a.cli_lvl_code, a.cli_title_code";if (Op_Ip.Value == "門診" || Op_Ip.Value == "急診"){strSQL = string.Format(strTmp, "1", "pctd_analysis_result_detail_op", acquisition_time, hosp_code, hos_adm_no);}else if (Op_Ip.Value == "住院"){strSQL = string.Format(strTmp, "2", "pctd_analysis_result_detail_ip", acquisition_time, hosp_code, hos_adm_no);}DataTable dt = helper.ExecuteQuery(strSQL);// 由于不想把多余的數據塞入result_level, 只能把datarow和result_level 弄成 KeyValuePair (數據-值對)形式SortedList<DataRow, result_level> levelList = new SortedList<DataRow, result_level>(new lvl_comparer());SortedList<DataRow, result_title> titleList = new SortedList<DataRow, result_title>(new lvl_title_comparer());SortedList<DataRow, result> resultList = new SortedList<DataRow, result>(new lvl_title_id_comparer());// 初始化所有result classforeach (DataRow row in dt.Rows){DataRow simpleRow = SimpleTable.NewRow();simpleRow["cli_lvl_code"] = row["cli_lvl_code"];simpleRow["cli_lvl_name"] = row["cli_lvl_name"];simpleRow["cli_title_code"] = row["cli_title_code"];simpleRow["cli_title_name"] = row["cli_title_name"];simpleRow["id"] = row["id"]; // 其它項都有可能相同,cli_analyze_title 會不同,但 cli_analyze_title 太長,換成以 "id" 為主鍵resultList.Add(simpleRow,new result(){Title = new title(){Value = model.deEncry(row["cli_analyze_title"].ToString()/*, Convert.ToInt32(row["encode_type"])*/)},Detail = new detail(){Value = model.deEncry(row["cli_analyze_addition"].ToString()/*, Convert.ToInt32(row["encode_type"])*/)},Reference = new reference(){Value = model.deEncry(row["cli_analyze_reference"].ToString()/*, Convert.ToInt32(row["encode_type"])*/)},result_id = simpleRow["id"].ToString()});}// 對result object 按 (cli_lvl_code - cli_title_code) 分組, 裝箱到 titleListIEnumerable<IGrouping<DataRow, KeyValuePair<DataRow, result>>> resultClique =resultList.GroupBy<KeyValuePair<DataRow, result>, DataRow>(keyValuePair => keyValuePair.Key,new lvl_title_equalitycomparer());foreach (IGrouping<DataRow, KeyValuePair<DataRow, result>> resultGroup in resultClique){result_title title = new result_title(){name = resultGroup.First().Key["cli_title_name"].ToString(),result = new result[resultGroup.Count()]};int i = 0;foreach (KeyValuePair<DataRow, result> resultMember in resultGroup){title.result[i] = resultMember.Value;i++;}titleList.Add(resultGroup.First().Key, title);}// 對result_title object 按 (cli_lvl_code) 分組, 裝箱到 levelListIEnumerable<IGrouping<DataRow, KeyValuePair<DataRow, result_title>>> titleClique =titleList.GroupBy<KeyValuePair<DataRow, result_title>, DataRow>(keyValuePair => keyValuePair.Key,new lvl_equalitycomparer());foreach (IGrouping<DataRow, KeyValuePair<DataRow, result_title>> titleGroup in titleClique){result_level level = new result_level(){name = titleGroup.First().Key["cli_lvl_name"].ToString(),result_title = new result_title[titleGroup.Count()]};int i = 0;foreach (KeyValuePair<DataRow, result_title> titleMember in titleGroup){level.result_title[i] = titleMember.Value;i++;}levelList.Add(titleGroup.First().Key, level);}// 生成 result_data class, 它最后賦值給網頁供顯示this.Result_data = new result_data(){name = "問題結果",result_level = new result_level[levelList.Count]};int j = 0;foreach (KeyValuePair<DataRow, result_level> levelMember in levelList){this.Result_data.result_level[j] = levelMember.Value;j++;}}

數據庫表結構:

pctd_analysis_result_detail_op 表


homh_user_analyze_rules_req 表



實現效果圖:
本次要屏蔽規則:
氨茶堿注射液≡≡維生素C注射液存在配伍禁忌
問題結果對應 result_data,
問題級別(重要警示,一般提示,其它信息)對應 result_level
問題標題(氨茶堿注射液≡≡維生素C注射液存在配伍禁忌)對應cli_title_name(cli_analyze_title, id 也可以)



在“屏蔽規則管理”中“批準”該屏蔽規則



批準屏蔽后,可以看到不會再顯示
氨茶堿注射液≡≡維生素C注射液存在配伍禁忌


參考例子:

http://msdn.microsoft.com/zh-cn/library/vstudio/bb534501.aspx

http://msdn.microsoft.com/zh-cn/library/vstudio/bb549393.aspx

class Pet{public string Name { get; set; }public double Age { get; set; }}public static void GroupByEx3(){// Create a list of pets.List<Pet> petsList =new List<Pet>{ new Pet { Name="Barley", Age=8.3 },new Pet { Name="Boots", Age=4.9 },new Pet { Name="Whiskers", Age=1.5 },new Pet { Name="Daisy", Age=4.3 } };// Group Pet objects by the Math.Floor of their age.// Then project an anonymous type from each group// that consists of the key, the count of the group's// elements, and the minimum and maximum age in the group.var query = petsList.GroupBy(pet => Math.Floor(pet.Age),(age, pets) => new{Key = age,Count = pets.Count(),Min = pets.Min(pet => pet.Age),Max = pets.Max(pet => pet.Age)});// Iterate over each anonymous type.foreach (var result in query){Console.WriteLine("\nAge group: " + result.Key);Console.WriteLine("Number of pets in this age group: " + result.Count);Console.WriteLine("Minimum age: " + result.Min);Console.WriteLine("Maximum age: " + result.Max);}/* This code produces the following output:Age group: 8Number of pets in this age group: 1Minimum age: 8.3Maximum age: 8.3Age group: 4Number of pets in this age group: 2Minimum age: 4.3Maximum age: 4.9Age group: 1Number of pets in this age group: 1Minimum age: 1.5Maximum age: 1.5*/}


總結

以上是生活随笔為你收集整理的c# SortedList的妙用 (GroupBy)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。