简体   繁体   English

比较 int 列表,同时考虑两个 int 如果重复则不相等

[英]Comparing lists of ints in, while considering two ints not to be equal if repeated

I know this question has been reiterated multiple times, and I think this is straightforward when using lists of reference types.我知道这个问题已被多次重申,我认为在使用引用类型列表时这很简单。 That is also what most questions talk about.这也是大多数问题所谈论的。 When doing this with value types, I can't quite figure it out.使用值类型执行此操作时,我无法弄清楚。

What I want do to is take an incoming request, and ensure that the request has at least the same numbers that are already present.我想要做的是接受一个传入的请求,并确保该请求至少具有已经存在的相同数字。 Additional numbers are allowed, and the additional numbers in the request will be persisted.允许附加号码,并且请求中的附加号码将被持久化。 So if [1,2] is already persisted and the request contains [1,2,3] , 3 will be persisted.因此,如果[1,2]已经被持久化并且请求包含[1,2,3] ,则3将被持久化。 If the request contained only 1 or 2 , that would be invalid, and [1,2] would be valid and only the data that already existed would be returned.如果请求只包含12 ,那将是无效的,并且[1,2]将是有效的,并且只会返回已经存在的数据。

The last case mentioned above I've implemented the following way:上面提到的最后一个案例我实现了以下方式:

Enumerable.SequenceEqual(existing.OrderBy(e => e), request.OrderBy(e => e));

When the lists aren't equal though, I want to treat each int in a list as if it was unique, but I can't figure out how to do this.但是,当列表不相等时,我想将列表中的每个 int 视为唯一的,但我不知道如何做到这一点。 In the following example, I would like the resulting list to be [1, 4] , but it ends up being [4] due to both the numbers 1 in the existing list are excluded due to being equal.在以下示例中,我希望结果列表为[1, 4] ,但由于现有列表中的两个数字1由于相等而被排除在外,因此最终结果为[4]

var existing = new List<int> { 1, 1, 2, 3, 4 };
var request = new List<int> { 1, 2, 3 };
existing.Except(request).ToList();
// 4

I have seen that Except accepts a IEqualityComparer , but I stumble when trying to implement this for a value type and I don't know if this is the correct way to go.我已经看到Except接受一个IEqualityComparer ,但是在尝试为值类型实现它时我绊倒了,我不知道这是否是 go 的正确方法。

Any help on how I should think when approaching this problem would be greatly appreciated.在处理这个问题时我应该如何思考的任何帮助将不胜感激。 Efficiency is not that important, as the lists will not contain many elements at all.效率并不那么重要,因为列表根本不会包含很多元素。

You could use regular List<T>.Remove(T) :您可以使用常规List<T>.Remove(T)

foreach(var e in existing)
{
    var actuallyExisted = request.Remove(e);
}

actuallyExisted will be false if it couldn't find e to remove.如果找不到要删除的eactuallyExisted将为 false。 request will now contain all int s that weren't in existing. request现在将包含所有不存在的int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM