gpt4 book ai didi

c# - 检查两个列表是否相等

转载 作者:IT王子 更新时间:2023-10-29 03:31:40 25 4
gpt4 key购买 nike

我有一个类如下:

public class Tag {
public Int32 Id { get; set; }
public String Name { get; set; }
}

我有两个标签列表:

List<Tag> tags1;
List<Tag> tags2;

我用了LINQ的选择以获取每个标签列表的 ID。然后:

List<Int32> ids1 = new List<Int32> { 1, 2, 3, 4 };
List<Int32> ids2 = new List<Int32> { 1, 2, 3, 4 };
List<Int32> ids3 = new List<Int32> { 2, 1, 3, 4 };
List<Int32> ids4 = new List<Int32> { 1, 2, 3, 5 };
List<Int32> ids5 = new List<Int32> { 1, 1, 3, 4 };

ids1 应该等于 ids2 和 ids3 ...两者具有相同的数字。

ids1 不应等于 ids4 和 ids5 ...

我尝试了以下方法:

var a = ints1.Equals(ints2);
var b = ints1.Equals(ints3);

但两者都给我假的。

检查标签列表是否相等的最快方法是什么?

更新

我正在寻找 TAGS 与 BOOK 中的 TAGS 完全相同的 POSTS。

IRepository repository = new Repository(new Context());

IList<Tags> tags = new List<Tag> { new Tag { Id = 1 }, new Tag { Id = 2 } };

Book book = new Book { Tags = new List<Tag> { new Tag { Id = 1 }, new Tag { Id = 2 } } };

var posts = repository
.Include<Post>(x => x.Tags)
.Where(x => new HashSet<Int32>(tags.Select(y => y.Id)).SetEquals(book.Tags.Select(y => y.Id)))
.ToList();

我正在使用 Entity Framework我得到了错误:

An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method 'Boolean SetEquals(System.Collections.Generic.IEnumerable`1[System.Int32])' method, and this method cannot be translated into a store expression.

我该如何解决?

最佳答案

使用SequenceEqual检查序列相等性,因为 Equals 方法检查引用相等性

var a = ints1.SequenceEqual(ints2);

或者,如果您不关心元素顺序,请使用 Enumerable.All方法:

var a = ints1.All(ints2.Contains);

第二个版本还需要对 Count 进行另一次检查,因为即使 ints2 包含的元素多于 ints1,它也会返回 true。所以更正确的版本应该是这样的:

var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;

为了检查不等式,只需反转All 方法的结果:

var a = !ints1.All(ints2.Contains)

关于c# - 检查两个列表是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22173762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com