Prescient
Prescient

Reputation: 1061

Filter a list on multiple columns

I need to filter my list based on multiple columns. here is my class that I need to search

public class psdata
    {
        public int ID { get; set; }
        public string Customer { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public decimal? Identification { get; set; }
        public decimal? Assesment { get; set; }
        public decimal? PayoffLedger { get; set; }
        public decimal? RentRestrictions { get; set; }
        public decimal? CCR { get; set; }
        public decimal SubTotal { get; set; }
    }

And here is my linq query that looks at my list and then will find the search term if it is contained in the column.

var sl = list.Where<psdata>( c => c.Address.ToLower().Contains(text));

This works great for the first column. However if I want to add another column as so.

var sl = list.Where<psdata>( c => c.Address.ToLower().Contains(text) || c => c.City.ToLower().Contains(text));

I get an error

Operator || cannot be applied to operands of the type bool and psdata.

What am I doing wrong here?

Upvotes: 2

Views: 10194

Answers (4)

evanmcdonnal
evanmcdonnal

Reputation: 48134

The problem is you're passing more than one lambda expression to where rather than using && or || in your lambda expression to combine multiple comparisons.

this; c => c.Address.ToLower().Contains(text) || c => c.City.ToLower().Contains(text)

should be; c => c.Address.ToLower().Contains(text) || c.City.ToLower().Contains(text)

Upvotes: 1

Touhid Alam
Touhid Alam

Reputation: 343

If you review the signature of Where clause, it's expecting a Func<TSource, Boolean>. Meaning you have to pass in a function that takes a type TSource, and returns boolean. We are passing an anonymous function as the argument. The syntax for anonymous function is, (argument)=>{ expression }. So, your code can be interpreted as

list.Where<psdata>(Func<psdata,bool>||Func<psdata,bool>)

which would obviously not behave as expected. So the solution would be

list.Where<psdata>(c => c.Address.ToLower().Contains(text) 
|| c.City.ToLower().Contains(text));

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245489

Your only issue is the second c =>. You're still only passing a single Lambda expression, it just needs to include the || operator:

var sl = list.Where(c => c.Address.ToLower().Contains(text) ||
    c.City.ToLower().Contains(text));

Upvotes: 9

jle
jle

Reputation: 9489

var sl = list.Where<psdata>( c => c.Address.ToLower().Contains(text) || c => c.City.ToLower().Contains(text));

should be

var sl = list.Where<psdata>( c => c.Address.ToLower().Contains(text) || c.City.ToLower().Contains(text));

You don't need the second 'goes to' => operator in your expression.

Upvotes: 2

Related Questions