简体   繁体   English

如何比较 C# 中的两个列表?

[英]How to compare two lists in C#?

I have two lists to compare:我有两个要比较的列表:

在此处输入图像描述

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.我想比较列表 A 和列表 B,如果列表 A 中存在列表 B 中的任何日期,则返回 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.例如,如果 14-01-2020(在列表 B 中)存在于列表 A(肯定存在)中,那么它应该返回 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.请注意:列表 A中的数据包含一整月的日期,而列表 B仅包含几个日期。

If any of the dates from ListB is present in List A then return true.如果 ListB 中的任何日期出现在 List A 中,则返回 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.哪个更适合您将取决于数据的性质,但我通常更倾向于在较短的序列上运行Contains()

Additionally, I see this:此外,我看到这个:

The data in List A contains the dates of an entire month列表 A 中的数据包含一整月的日期

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.最后,如果您知道其中一个或两个序列中的数据已排序,则可以显着优化这些数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM