c#比较集合
本文关键字:集合 比较 | 更新日期: 2023-09-27 18:12:36
我是c#新手,需要一些比较集合的帮助。我有两个List<string>
集合,其内容如下:
收集旧:{"AAA"、"BBB"、"CCC"}
收集新:{" BBB ","CCC"、"DDD"}
我想要一个像下面这样的集合:
集合最终:{"AAA","删除";"BBB"、"保持";"CCC"、"保持";"DDD","添加"}
我该怎么做?
old.Except(new)
会给你那些要删除的项目
new.Except(old)
会给你添加的项目
old.Intersect(new)
会给你物品保存
(这是假设你不介意使用系统。Linq命名空间)
或者,如果您愿意,您可以单独考虑每个项并检查每个列表中的存在
var oldList = new List<String>() {"AAA", "BBB", "CCC"};
var newList = new List<String>() {"BBB", "CCC", "DDD"};
var diffDictionary = new Dictionary<string, string>();
foreach (var oldEntry in oldList)
{
diffDictionary.Add(oldEntry, "Remove");
}
foreach (var newEntry in newList)
{
if (diffDictionary.ContainsKey(newEntry))
{
diffDictionary[newEntry] = "Keep";
}
else
{
diffDictionary.Add(newEntry, "Add");
}
}
foreach (var dDico in diffDictionary)
{
Console.WriteLine(string.Concat("Key: ", dDico.Key, " Value: ", dDico.Value));
}
您可以使用字典来完成此操作…
最后,字典中的每个元素会告诉你每种元素被删除或添加了多少项。
它将用一个计数来表示,而不是简单的3个状态标志…这是因为你可能添加或删除了重复的项目……如果在第二个集合中插入3个AAA
呢?
string[] col1 = new string[] { "AAA", "BBB", "CCC" };
string[] col2 = new string[] { "BBB", "CCC", "DDD" };
Dictionary<string, int> colDic = new Dictionary<string, int>();
foreach (var item in col1)
{
int num;
if (colDic.TryGetValue(item, out num))
colDic[item] = num - 1;
else
colDic[item] = -1;
}
foreach (var item in col2)
{
int num;
if (colDic.TryGetValue(item, out num))
colDic[item] = num + 1;
else
colDic[item] = 1;
}
最终结果如下所示:
AAA = -1
BBB = 0
CCC = 0
DDD = 1
一行(sort of)!
string[] colOld = {"AAA","BBB","CCC"};
string[] colNew = {"BBB","CCC","DDD"};
dynamic colALL = (from o in colOld.Union(colNew)
select new {Value = o, Action =
colOld.Any(s => s == o) ?
colNew.Any(s => s == o) ? "Keep" : "Remove"
: "Add"
}).ToList();
注意:这是一个开发者的融合转换下面的vb.net的工作-我还没有机会测试c#版本:
Dim colOld() As String = {"AAA", "BBB", "CCC"}
Dim colNew() As String = {"BBB", "CCC", "DDD"}
Dim colALL = (From o As String In colOld.Union(colNew) _
Select New With {.Value = o, .Action = _
If(colOld.Any(Function(s) s = o), _
If(colNew.Any(Function(s) s = o), "Keep", "Remove"), _
"Add")}).ToList
如果你有这个方法
public static IEnumerable<T> Concat<T>(params IEnumerable<T>[] sequences)
{
return sequences.SelectMany(x => x);
}
你应该能够写:
static readonly string Remove = "Remove";
static readonly string Keep = "Keep";
static readonly string Add = "Add";
var result = Concat
(
old.Except(new).Select(x => new { x, Remove }),
old.Intersect(new).Select(x => new { x, Keep }),
new.Except(old).Select(x => new { x, Add })
);
当然你可以使用内置的Enumerable.Concat
方法,但我觉得我的更优雅。