检查两个列表是否相等 [英] Check if two lists are equal
问题描述
我有一个类如下:
public class Tag {
public Int32 Id { get; set; }
public String Name { get; set; }
}
我有两个标签列表:
List<Tag> tags1;
List<Tag> tags2;
我使用 LINQ 的选择来获取每个标签列表的 Id.然后:
I used LINQ's select to get the Ids of each tags list. And then:
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 should be equal to ids2 and ids3 ... Both have the same numbers.
ids1 不应等于 ids4 和 ids5 ...
ids1 should not be equal to ids4 and to ids5 ...
我尝试了以下方法:
var a = ints1.Equals(ints2);
var b = ints1.Equals(ints3);
但两者都给我错误.
检查标签列表是否相等的最快方法是什么?
What is the fastest way to check if the lists of tags are equal?
更新
我正在寻找标签与书籍中的标签完全相同的帖子.
I am looking for POSTS which TAGS are exactly the same as the TAGS in a BOOK.
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();
我正在使用 实体框架,但出现错误:
I am using Entity Framework and I get the error:
mscorlib.dll 中出现类型为System.NotSupportedException"的异常,但未在用户代码中处理
An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code
附加信息:LINQ to Entities 无法识别方法 'Boolean SetEquals(System.Collections.Generic.IEnumerable`1[System.Int32])' 方法,并且该方法无法转换为存储表达式.
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.
我该如何解决这个问题?
How do I solve this?
推荐答案
使用 SequenceEqual
检查序列是否相等,因为 Equals
方法检查引用相等.
var a = ints1.SequenceEqual(ints2);
或者,如果您不关心元素顺序,请使用 Enumerable.All
方法:
Or if you don't care about elements order use Enumerable.All
method:
var a = ints1.All(ints2.Contains);
第二个版本还需要对 Count
进行另一次检查,因为即使 ints2
包含的元素多于 ints1
,它也会返回 true.所以更正确的版本应该是这样的:
The second version also requires another check for Count
because it would return true even if ints2
contains more elements than ints1
. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
为了检查不等式只需反转All
方法的结果:
In order to check inequality just reverse the result of All
method:
var a = !ints1.All(ints2.Contains)
这篇关于检查两个列表是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!