0

i have this class:

   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>();

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");

2 Answers 2

3

Well, you could just use:

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

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.

Sign up to request clarification or add additional context in comments.

3 Comments

If i use the first give me an error : Value can not be null. Parameter name: first . Why ? Thanks
@enzop92: Well that suggests that one of your references is null. However, as you haven't even said which method call is failing, it's hard to tell you which... I suggest you look at your data carefully.
Jon Thank you so much.. U are very kind !
2
arts.SelectMany(a => a.BarCode).Intersect(eans).Any()

should be an efficient way of doing this, if I understand your problem correctly.

arts.SelectMany(a => a.BarCode)

flattens all the BarCode collections to an Enumerable<Ean>, which you can then intersect with your other collection and see if anything is left.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.