检查两个列表是否具有相同的项目 [英] Check if two list have the same items

查看:48
本文介绍了检查两个列表是否具有相同的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个如下列表,我怎么能说它们具有相同的元素.顺序并不重要.

I have two lists as below, how can I say that they have the same elements. The order is not important.

var list1 = new List<int> {1,2,3};
var list2 = new List<int> {2,1,3};

我怎么能说这是相等的?我应该编写自己的方法还是内置方法?

How can I say that these are equal? Should I write my own method or is there a built-in method for it?

推荐答案

这就是设置的内容(例如, SetEquals 验证集合和另一个集合是否包含相同的元素.

That's what sets (e.g., HashSet<T>) are for. Sets have no defined order, and SetEquals verifies whether the set and another collection contain the same elements.

var set = new HashSet<int>(list1);
var equals = set.SetEquals(list2);

这篇关于检查两个列表是否具有相同的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆