我通过执行 String.Split() 创建了 3 个字符串列表。之后,当我在这些列表上进行相交时,结果不是我所期望的。代码 1(不工作)
string a = "AID, BID";
string b = "[vs|AID|1365]";
string c = "[vs|BID|1365]";
List<string> la = new List<string>();
string[] k = a.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string p in k)
{
la.Add(p);
}
//la.AddRange(k.ToList());
List<string> lb = new List<string>();
string[] kk = b.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string p in kk)
{
lb.Add(p);
}
//lb.AddRange(kk.ToList());
List<string> lc = new List<string>();
string[] kkk = c.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string p in kkk)
{
lc.Add(p);
}
//lc.AddRange(kkk.ToList());
var t = la.Intersect(lb, StringComparer.InvariantCultureIgnoreCase);
Debug.WriteLine(t.Count()); //Prints 1 -- RIGHT
var tt = la.Intersect(lc, StringComparer.InvariantCultureIgnoreCase);
Debug.WriteLine(tt.Count()); //Prints 0 -- WRONG!!!
我尝试了 AddRange,但也没有用。我注意到的另一件事是,如果我在“字符串 a”分配中更改了 AID 和 BID 的顺序,则 intersect 会找到 BID 但不会找到 AID。不知道为什么?
上述例程的硬编码版本可以正常工作
List<string> la = new List<string>(); la.Add("AID"); la.Add("BID");
List<string> lb = new List<string>(); lb.Add("[vs"); lb.Add("AID"); lb.Add("1365]");
List<string> lc = new List<string>(); lc.Add("[vs"); lc.Add("BID"); lc.Add("1365]");
var t = la.Intersect(lb, StringComparer.InvariantCultureIgnoreCase);
Debug.WriteLine(t.Count()); //Prints 1.
var tt = la.Intersect(lc, StringComparer.InvariantCultureIgnoreCase);
Debug.WriteLine(tt.Count());//Prints 1.
更新:下面是我最终得到的代码。
string a = "AID, BID";
string b = "[vs|AID|1365]";
string c = "[vs|BID|1365]";
List<string> tla = a.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim()).ToList();
List<string> tlb = b.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim()).ToList();
List<string> tlc = c.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim()).ToList();
var t = tla.Intersect(tlb, StringComparer.InvariantCultureIgnoreCase);
var tt = tla.Intersect(tlc, StringComparer.InvariantCultureIgnoreCase);