![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Dictionary<string, string> odce = new Dictionary<string, string>();//字典 良好的判断是否为空的集合 int s=0; Console.WriteLine ("开始检测类id重复情况"); XElement root = XElement.Load(@"E:\lixinhai\实验\qq.xml"); Console.WriteLine("开始读取"); StreamWriter writer = new StreamWriter(@"C:\Documents and Settings\Administrator\桌面\tt.txt", false, Encoding.GetEncoding("GB2312")); IEnumerable <XElement> oolist =from ele in root.Elements() where ele.Attributes().FirstOrDefault().Name.LocalName=="ID" select ele; foreach (XElement item in oolist) { string ss=item.Attributes().FirstOrDefault().Value; string tt = item.Value.ToString(); string pp=item.Name.LocalName.ToString(); string kk = string.Empty; try { s++; odce.Add(ss, pp); } catch (ArgumentException) { //Console.WriteLine("An element with Key {0} already exists.", ss); Console.WriteLine("设备ID:"+ss+"有重复"); // Console.WriteLine("名称是" kk.ToString()); writer.WriteLine("duplicate:" + ss); writer.WriteLine("名称是:" + pp + ""); } catch(Exception e) { Console.WriteLine(e.ToString()); } } Console.WriteLine(s.ToString()+"检测类"); Console.WriteLine(odce.Count.ToString()); Console.WriteLine("ok ! ********************************************** "); writer.Flush(); //若想输出类内情况 ,把下面的代码改写一下 writer.Close(); Console.WriteLine("按下任意键开始,检测类内重复情况"); Console.ReadKey(); int i= 0; int j = 0; Dictionary <string ,string> openwith=new Dictionary<string,string>(); IEnumerable <XElement> llist =from ele in root.Elements() where ele.Attributes().FirstOrDefault().Name.LocalName=="ID" select ele; foreach (XElement alist in llist) { IEnumerable<XElement> ss = from app in alist.Elements() select app ; foreach (XElement ass in ss) { string wherestr = ss.FirstOrDefault().Value.ToString().ToLower().Trim(); //(第一个元素) string bb = ass.Name.LocalName.ToString().ToLower().Trim(); string kk = wherestr + bb; try { i = i + 1; openwith.Add(kk, wherestr); } catch (ArgumentException) { Console.WriteLine("An element with Key {0} already exists.", kk); // Console.WriteLine(odce.Count.ToString()); j++; } } } Console.WriteLine(i.ToString() + "检测类内列重复完成"); Console.WriteLine("ok"); Console.WriteLine(openwith.Count.ToString()); Console.WriteLine(j.ToString() + "**************************************"); } }