根据对象c#的另一个列表搜索对象列表 [英] Search list of object based on another list of object c#

查看:85
本文介绍了根据对象c#的另一个列表搜索对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程:

   class Ean
   {
        public string Code{ get; set; }
   }

   class Article
   {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Ean> BarCode { get; set; }
   }


   List<Article> arts = new List<Article>();
   List<Ean> eans = new List<Ean>();

我有两个对象的列表.我需要检查列表"arts.BarCode"中是否有eans列表中的代码之一.如何使此搜索返回布尔值? 任何帮助将是巨大的!谢谢!

I have a list of two objects. I need to check if in the list "arts.BarCode" there is one of the codes in the list eans. How can I do to make this search returns a Boolean value? Any help would be great! Thanks!

像这样的东西会很完美:

something like this would be perfect:

bool hasCheese = arts.Any(a => a.Name == "Cheese");

推荐答案

好吧,您可以只使用:

bool hasCode = arts.Any(a => a.BarCode.Intersect(eans).Any());

假设您要分别对待每个Ean对象的 ,或者您实际上已经适当地覆盖了EqualsGetHashCode.

That's assuming that either you want to treat each Ean object individually, or you've actually overridden Equals and GetHashCode appropriately.

尽管创建一个集会更有效:

It would be more efficient to create a set though:

var set = new HashSet<Ean>(eans);
bool hasCode = arts.Any(a => a.BarCode.Any(e => set.Contains(e)));

作为一种替代方法,您可以将列表展平为基本上是条形码的序列:

As an alternative approach, you could flatten your list to basically be a sequence of barcodes:

bool hasCode = arts.SelectMany(a => a.BarCode)
                   .Intersect(eans)
                   .Any();

这实际上可能是最干净的方法,因为您并不关心哪一文章具有匹配的条形码.

That's actually probably the cleanest approach, as you don't care about which article has the matching barcode.

这篇关于根据对象c#的另一个列表搜索对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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