user1263981
user1263981

Reputation: 3157

Filter Generic List by multiple values

There is a generic list of documents, how can i filter it by doc id 1 and 2.

I have tried following Linq but it is not working. I need to filter list and use it as a data source.

List<VisitDocs> listD = default(List<VisitDocs>);
result = from docs in listDwhere docs.DocID == 1 && docs.DocID == 2docs;

rptDocs.DataSource = listD;

Upvotes: 0

Views: 1352

Answers (4)

AFract
AFract

Reputation: 9700

I think you tried to write something like this :

var result = (from docs in listD
             where docs.DocID == 1 || docs.DocID == 2
             select docs).ToList();

rptDocs.DataSource = result;

Where listD is your original list. Please note that in your code sample, ListD will be empty.

If you wish results with both DocID values 1 and 2, simply replace "&&" by "||". With "&&" it means that any single result should valid both conditions, which is impossible : a single result will have DocID equals to 1, or 2, or anything else. So if you want to take every result with 1 "or" 2, you should use the OR logical operator.

Upvotes: -1

Habib
Habib

Reputation: 223392

You need ||:

result = listD.Where(doc=> doc.DocID == 1 || doc.DocID == 2);

or

result = from docs in listD where docs.DocID == 1 || docs.DocID == 2 select docs;

Your DocID could be 1 or 2, It can't be both. Your current condition is using && which would mean that it must be 1 and 2 at the same time.

For assigning DataSource call ToList like:

rptDocs.DataSource = result.ToList();

Upvotes: 3

marcoaoteixeira
marcoaoteixeira

Reputation: 505

Please, change && to || and see if it works

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292685

docs.DocID == 1 && docs.DocID == 2 can never be true: if the value is 1, it's not 2, and vice versa. You need to use || (or), not && (and)

Upvotes: 1

Related Questions