简体   繁体   中英

How to check search text contains in any field

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?

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))
); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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