1

I have two lists to compare:

enter image description here

I want to compare List A and List B such that if any of the dates from ListB is present in List A then return true.

For example, if 14-01-2020 (which is in List B) is present in List A (which is definitely present) then it should return true.

How to do that?

Please note: The data in List A contains the dates of an entire month, whereas List B contains only a few dates.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
  • 10
    How about `ListA.Any(dt => ListB.Contains(dt))` ? – Lasse V. Karlsen Apr 10 '20 at 17:10
  • I think this has been already answered here: [https://stackoverflow.com/questions/3669970](https://stackoverflow.com/questions/3669970/compare-two-listt-objects-for-equality-ignoring-order) – Stratis Dermanoutsos Apr 10 '20 at 17:13
  • Does this answer your question? [Compare two lists of object for new, changed, updated on a specific property](https://stackoverflow.com/questions/23581379/compare-two-lists-of-object-for-new-changed-updated-on-a-specific-property) – Michael Freidgeim Apr 10 '20 at 17:16

1 Answers1

5

If any of the dates from ListB is present in List A then return true.

 return ListB.Any(x => ListA.Contains(x));

or vice versa:

 return ListA.Any(x => ListB.Contains(x));

Which one is better for you will depend on the nature of your data, but I'd normally favor running Contains() over the shorter sequence.

Additionally, I see this:

The data in List A contains the dates of an entire month

Depending on exactly what you mean, you may be able to take advantange of that fact:

var start = A.Min(x => x);
var stop = A.Max(x => x);
return ListB.Any(x => x >= start && x <= stop);

Finally, if you know the data in one or both of the sequences is sorted, you can optimize these significantly.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Thanks @Joel, I will definitely try this. It's sleep time. I will accept it asap if it works. Thanks for your help!: ) – Rohan Rao Apr 10 '20 at 17:48