检查一个IEnumerable是否包含另一个IEnumerable的所有元素 [英] Check if one IEnumerable contains all elements of another IEnumerable

查看:75
本文介绍了检查一个IEnumerable是否包含另一个IEnumerable的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在比较两个集合中每个元素的字段/属性时,确定一个IEnumerable是否包含另一个IEnumerable的所有元素的最快方法是什么?

What is the fastest way to determine if one IEnumerable contains all the elements of another IEnumerable when comparing a field/property of each element in both collections?

public class Item
{
    public string Value;

    public Item(string value)
    {
        Value = value;
    }
}

//example usage

Item[] List1 = {new Item("1"),new Item("a")};
Item[] List2 = {new Item("a"),new Item("b"),new Item("c"),new Item("1")};

bool Contains(IEnumerable<Item> list1, IEnumerable<Item>, list2)
{
    var list1Values = list1.Select(item => item.Value);
    var list2Values = list2.Select(item => item.Value);

    return //are ALL of list1Values in list2Values?
}

Contains(List1,List2) // should return true
Contains(List2,List1) // should return false

推荐答案

除非您跟踪并维护确定一个集合中的所有值是否包含在另一个集合中的某些状态,否则没有快速方法"来执行此操作.如果您只有IEnumerable<T>可以使用,我会使用Intersect.

There is no "fast way" to do this unless you track and maintain some state that determines whether all values in one collection are contained in another. If you only have IEnumerable<T> to work against, I would use Intersect.

var allOfList1IsInList2 = list1.Intersect(list2).Count() == list1.Count();

此功能应该非常合理,因为Intersect()只会对每个列表进行一次枚举.另外,如果基础类型是ICollection<T>而不只是IEnumerable<T>,则对Count()的第二次调用将是最佳选择.

The performance of this should be very reasonable, since Intersect() will enumerate over each list just once. Also, the second call to Count() will be optimal if the underlying type is an ICollection<T> rather than just an IEnumerable<T>.

这篇关于检查一个IEnumerable是否包含另一个IEnumerable的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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