How to check search text contains in any field

Viewed 35

I Have a list data called LogData. Its code something like this.

var LogData = LogDataList.Select(data => new LogDataDto
{
    RowCount = RowCount,
    Location = data.LocationName,             
    Sender = data.FullName,
    AccountName = data.AccName,
    Messsage = data.Message
}).ToList();

Application gives me front-end value called searchText. I need to check that search text value is consists in any field in LogData

When searchText = "" I need to get all in the LogData and If searchText have some value, I need to check that value consist in any of this filels Location,Sender,AccountName and Messsage and nee to get those records.

So tried it as,

var result = LogData.Where(x => (searchText == "" || x.Location.Contains(searchText)) || x.Messsage.Contains(searchText)); 

Is that correct way to do this? How can I check search text value contains in other filed as well?

1 Answers

If you need to search on four fields, you can continue to expand your OR conditions to include the additional fields.

var result = LogData.Where(x => (
    searchText == "" || 
    x.Location.Contains(searchText) || 
    x.Messsage.Contains(searchText) || 
    x.Sender.Contains(searchText) ||
    x.AccountName.Contains(searchText))
); 

As Charlieface mentioned, you can potentially optimize this a bit by treating searchText == "" as an early exit condition and return your collection without a where clause.

var result = searchText == "" ? LogData : LogData.Where(x => (
    x.Location.Contains(searchText) || 
    x.Messsage.Contains(searchText) || 
    x.Sender.Contains(searchText) ||
    x.AccountName.Contains(searchText))
); 
Related