Za7pi
Za7pi

Reputation: 1418

Filter datatable with Linq by a decimal list in c#

I have got a datatable and I want to filter by a value. This is working:

 var result = datatable.AsEnumerable()
    .Where(r => r.Field<decimal?>("decimal_col") == 1);

Now I want to filter by a list of decimals. I have tried to put contains but it is not working. This is the list:

var list = new List<decimal>() { 8, 3, 2, 1 };

And this is what I want, but it is not working:

var result = datatable.AsEnumerable()
        .Where(r => r.Field<decimal?>("decimal_col").Contains(list));

Any help?

Upvotes: 0

Views: 1060

Answers (2)

Anu Viswan
Anu Viswan

Reputation: 18155

You need to use list.Contains(). The syntax is List<T>.Contains(item) (Note the difference, In the query in OP, it was in correctly given as item.Contains(list))

var result = datatable.AsEnumerable()
        .Where(r => list.Contains(r.Field<decimal?>("decimal_col")));

You can read more on the syntax of List.Contains here

Upvotes: 5

David
David

Reputation: 218827

You're checking if the value "contains" the list. It's the other way around. The list would "contain" the value:

list.Contains(r.Field<decimal?>("decimal_col"))

Upvotes: 1

Related Questions