如果我有2个大小为5的哈希集,我如何从第一个哈希集中获取x项并将它们与第二个哈希集中的x项交换?
例如 :
HashSet 1 has elements = {a , b, c , d ,e}
HashSet 2 has elements = {r , s ,t ,u , w}
Run Code Online (Sandbox Code Playgroud)
交换后我想获得:
HashSet 1 = {r, s , c ,d e}
HashSet 2 = {a, b, t , u ,w}
Run Code Online (Sandbox Code Playgroud)
我不需要特别的订单.
也许:
HashSet<string> hash1 = new HashSet<string>() { "A1", "B1", "C1", "D1" };
HashSet<string> hash2 = new HashSet<string>() { "A2", "B2", "C2", "D2" };
var firstThreeInOne = hash1.Take(3).ToList();
var firstThreeInTwo = hash2.Take(3).ToList();
foreach (string str in firstThreeInOne)
hash1.Remove(str);
foreach (string str in firstThreeInTwo)
hash2.Remove(str);
foreach (string str in firstThreeInTwo)
hash1.Add(str);
foreach (string str in firstThreeInOne)
hash2.Add(str);
Run Code Online (Sandbox Code Playgroud)
测试:
Console.WriteLine(string.Join(",", hash1)); // C2,B2,A2,D1
Console.WriteLine(string.Join(",", hash2)); // C1,B1,A1,D2
Run Code Online (Sandbox Code Playgroud)
但请注意,HashSet不保证插入顺序.它根本不是一个有序的集合.
MSDN明确提到:
本
HashSet<T>类提供高性能的设置操作.集合是一个不包含重复元素的集合,其元素没有特定的顺序.
| 归档时间: |
|
| 查看次数: |
215 次 |
| 最近记录: |