C#从列表中删除重复的字典项<>
本文关键字:字典 lt gt 列表 删除 | 更新日期: 2023-09-27 18:00:59
所以我在一个列表中收集了字典项:
List<Dictionary<string, string>> inputData = new List<Dictionary<string, string>>(inputs);
List<Dictionary<string, string>> itemStack = new List<Dictionary<string, string>>();
现在我要做的是,对于每个inputData字典项,我要检查itemStack是否已经具有相同的值(dictionary item(。
我在想会是什么样子?
foreach (var item in inputData)
{
if(!itemStack.Contains(item){ itemStack.Add(item)}
else{ //Duplicate found}
}
它并没有真正检查里面的项值?它只是假设它没有。。。我想要的只是如果itemStack包含,而已经在堆栈中的项不包含它。我知道我错过了一些显而易见的东西。谢谢,
Dictionary是引用类型,因此它不会像您预期的那样检查"deep"值。
您必须编写自己的"Contains"方法,作为完全独立的方法或Dictionary本身的扩展,然后使用它,例如:
if(!MyContains(itemStack, item)){ itemStack.Add(item)}
确实,HashSet会更好,但如果你想在这里做到这一点,试试这个(假设你只过滤重复的密钥(:
foreach (var item in inputData.Keys)
{
if (itemStack.Where(x => x.Key == item.Key).Count() > 0)
// There was a duplicate
}
或者,如果你只关心数据何时出来,你可以拨打:
itemStack.Distinct()
我认为,你的方式是正确的。在我看来,HashSet是好的,但当您添加一个新元素时,它会对相同项的内容执行相同的测试。
谨致问候。
根据您最初的问题陈述,您可能会执行以下操作:
var aggregateKnownKeys = itemStack.SelectMany(d => d.Keys);
itemStack.AddRange(
inputData.Select(d=> d.Where(p => !aggregateKnownKeys.Contains(p.Key))
.ToDictionary(p => p.Key, p => p.Value)));
如果你只需要组合两个字典,那么你可以跳过itemStack:中存在的键
var inputData = new Dictionary<string, string>();
var itemStack = new Dictionary<string, string>();
var oldStack = itemStack;
itemStack = new[] { inputData.SkipWhile(d => oldStack.Keys.Contains(d.Key)), itemStack }
.SelectMany(d => d)
.ToDictionary(d => d.Key, d => d.Value);
好吧,这不是一个完整的答案,但我就是这么做的。
所以我有一个项目列表,而不是与列表中的内容进行全面比较(因此考虑了其他内容(,我只做了一个项目检查:
if(!String.IsNullOrEmpty(item["itemId"]))
{
alert.DaleksApproaching(item["itemId"]);
}
因此,当它看到它有价值时,它只会做另一件事来摆脱它。我喜欢使用LINQ的想法和关于(Contains和Distinct(的方法。我还没有尝试过,但我计划这么做。为此,它不使用LINQ:(
谢谢大家!