How compare on Linq Where Datetime to Array

MiguelBT 96 Reputation points
2023-05-10T09:38:33.8866667+00:00

Hi,

I intend to compare the dates in a list with the dates in an array.

I tried to compare converting to string but without result:

string [] _search_date;
result = result.Where(x => _search_date.Contains(x.mp_orders.dateOrder.Value.ToString())).ToList();

I tried converting my string array to datetime array to intersect but with no result.:

List<DateTime?> _search_datetime = new List<DateTime?>();
foreach (string item in _search_date)
{
	_search_datetime.Add(Convert.ToDateTime(item));
}
result = result.Where(x => _search_datetime.Intersect(x.mp_orders.dateOrder)).ToList();

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,417 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2023-05-10T17:15:18.2133333+00:00

    Intersect() returns a new collection of matching elements, not bool. assuming dateOder is a collection then it is:

    .Where(x => _search_datetime.Intersect(x.mp_orders.dateOrder).Count() > 0);

    0 comments No comments

  2. Lan Huang-MSFT 28,841 Reputation points Microsoft Vendor
    2023-05-11T06:57:49.7866667+00:00

    Hi @MiguelBT,

    From your code, mp_orders.dateOrder should be of type List<DateTime?>.

    You can also use the following code:

    result = result.Where(x => _search_datetime.Intersect(x.mp_orders.dateOrder).Any()).ToList();

    Enumerable.Any Method:Determines whether any element of a sequence exists or satisfies a condition.

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments