Can you use an array inside of .Contains() via LINQ?

muttBunch 100 Reputation points
2023-12-21T07:32:08.6533333+00:00

Please see the very bottom in the Answers section from me, I updated question down there rather than removing this here.


A co-worker and myself wrote a very small app to store logs in a SQL database for 6 months. I'd like to add filtering parameters to it. Example, any keyword or multiple keywords in the description property and have it return any event containing those keywords.

I have the below "events" LINQ query. I would like to know if it's possible to use an array inside of .Contains() in the LINQ query? Or is there a much better suggestion?

Class:

public class LogStore
{    
	public int Id { get; set; }
	public int? EventId { get; set; }
	public DateTime? TimeStamp { get; set; }
	public string? TaskCategory { get; set; }
	public string? Description { get; set; }
}

Service:

private readonly ApplicationDbContext _applicationDbContext;

public EventsManagementService(ApplicationDbContext applicationDbContext)
{
    _applicationDbContext = applicationDbContext;    
}

public async Task<List<LogStore>> GetEvents(CancellationToken token)
{

	try
	{
		var events = await _applicationDbContext.LogStore
			.AsNoTracking()
			.OrderByDescending(x => x.TimeStamp)
			.ToListAsync(cancellationToken: token);
		
		return events;
	}
	catch (OperationCanceledException)
	{
		return new List<LogStore>();
	}
	      
}

Controller:

[HttpGet("GetEvents")]
public async Task<ActionResult<List<LogStore>>> GetEvents(CancellationToken token)
{
    
    return Ok(new { data = await _eventsManagementService.GetEvents(token) });

}

Thank you kindly.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
719 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
314 questions
{count} votes

Accepted answer
  1. Tahir KÖŞKEROĞLU 80 Reputation points
    2023-12-21T09:18:27.74+00:00

    Yes, you can easily search for events based on specific keywords within their descriptions. To do this, you'll use a LINQ queries that combines Any and Contains methods. This dynamic duo will help you pinpoint the events that match your keywords.

    Service:

    public async Task<List<LogStore>> GetEvents(string[] keywords, CancellationToken token)
    {
        try
        {
            var events = await _applicationDbContext.LogStore
                .AsNoTracking()
                .Where(x => keywords.Any(keyword => x.Description.Contains(keyword)))
                .OrderByDescending(x => x.TimeStamp)
                .ToListAsync(cancellationToken: token);
    
            return events;
        }
        catch (OperationCanceledException)
        {
            return new List<LogStore>();
        }
    }
    
    

    Controller:

    [HttpGet("GetEvents")]
    public async Task<ActionResult<List<LogStore>>> GetEvents([FromQuery] string[] keywords, CancellationToken token)
    {
    	var events = await _eventsManagementService.GetEvents(keywords, token);
    	return Ok(new { data = events });
    }
    
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. muttBunch 100 Reputation points
    2023-12-23T01:31:34.2766667+00:00

    Maybe I was wrong on my initial question in regards to using an array. I want to do something once, instead of with multiple "&&" for the .Where clause, but not hardcoding them as I want them to be parameters. Basically searching the description for anything containing the text keywords for parameters.

    Instead of something such as this...

    .Where(x => x.description.Contains("text") && x.description.Contains("text")
    	&& x.description.Contains("text")" && x.description.Contains("text"));
    

    I tried Tahir's solution and using it with parameter:

    http://localhost/api/v2/Events/GetEvents?keywords=testdemo,administrator,test.local,domain

    But it didn't work for me. I would like it to work exactly as the URL with ?keywords=blah,blah1,blah2,blah3

    I also need to do the same for INTs for the EventId's.

    Thanks

    0 comments No comments