巧用字典异常 捕获两个字符串(或者数组)中的相同元素

 

using System;
using System.Collections.Generic;
using System.Text;

  

Dictionary<string, int> oldZDXX = new Dictionary<string, int>();
string[] aa ="GLBXNAME,GLZD,GLOO,GLZDID".Split(',');
int coutaa = aa.Length;
for (int i = 0; i < coutaa; i++)
{
oldZDXX.Add(aa[i],i);
}
StringBuilder xx1 = new StringBuilder();
string[] newZDXX="GLBXNAME,GLXX,GLOO".Split(',');
int newZDXXCOUNT=newZDXX.Length;
for(int i=0;i<newZDXXCOUNT;i++)
{
try    {
oldZDXX.Add(newZDXX[i],i);}
catch{
if(xx1.ToString()=="")    
xx1.Append(newZDXX[i]);
else
xx1.Append(","+newZDXX[i]);
}
}
Console.WriteLine("oldZDXX已经存在元素"+xx1.ToString());

 

 

 

同时可以参考 http://www.cnblogs.com/50614090/archive/2011/09/06/2169019.html 

1.  取交集 (A和B都有)

List A : { 1 , 2 , 3 , 5 , 9 }
List B : { 4 , 3 , 9 }
var intersectedList = list1.Intersect(list2);
结果 : { 3 , 9 }
判断A和B是否有交集 bool isIntersected = list1.Intersect(list2).Count() > 0

2. 取差集 (A有,B沒有)
List A : { 1 , 2 , 3 , 5 , 9 }
List B : { 4 , 3 , 9 }
 var expectedList = list1.Except(list2);
结果 : { 1 , 2 , 5 }
判断A和B是否有差集 bool isExpected = list1.Expect(list2).Count() > 0

 3.  取联集 (包含A和B)

var unionList =list1.Union(list2);

  

 

posted @ 2014-07-02 18:33  博客园董事长  阅读(156)  评论(0编辑  收藏  举报